API Reference
This page contains detailed API reference documentation for all True-Core modules.
Enum Management
EnumRegistry
- class true.enum_registry.EnumRegistry(enums=None, duplication=False)[source]
Bases:
Generic[T]A sophisticated class for combining and managing multiple Enum classes with advanced functionality. Supports arithmetic operations between CombineEnums instances and Enum classes.
Features: - Combines multiple Enum classes into a single manageable entity - Supports arithmetic operations (addition, subtraction, etc.) - Supports iteration, comparison, and membership testing - Provides value validation and duplicate detection - Includes serialization/deserialization capabilities - Implements custom string representations - Supports advanced filtering and query operations
- Parameters:
enums (Iterable[Type[Enum]]) – Collection of Enum classes to combine
duplication (bool, optional) – Whether to allow duplicate values. Defaults to False.
- __init__(enums=None, duplication=False)[source]
- property metadata: EnumMetadata
Returns the metadata associated with the enum registry.
- register(enums)[source]
Register new enums to the registry.
- Return type:
- deregister(enums)[source]
Deregister enums from the registry.
- Return type:
- dregister(enum_class=None)[source]
Decorator to register an enum class.
- members_of(enum_class)[source]
Get all enum members from a specific enum class.
- _create_filtered_instance(members)[source]
Helper method to create new instance from filtered members.
- Return type:
- statistics()[source]
Get comprehensive statistics about the registry :returns: An EnumStats dataclass instance :rtype: EnumStats
- members()[source]
Group members by their original enum class.
- merge(*combine_enums)[source]
Merge multiple CombineEnums instances into a new instance.
- Return type:
- __add__(other)[source]
Add another CombineEnums instance or Enum class to this instance. Returns a new CombineEnums instance containing members from both operands.
- Parameters:
other (
Union[EnumRegistry,Type[Enum]]) – Another CombineEnums instance or Enum class- Returns:
A new instance containing combined members
- Return type:
- Raises:
IncompatibleTypesError – If other is not a CombineEnums instance or Enum class
- __sub__(other)[source]
Subtract another CombineEnums instance or Enum class from this instance. Returns a new CombineEnums instance containing members only from this instance.
- Parameters:
other (
Union[EnumRegistry,Type[Enum]]) – Another CombineEnums instance or Enum class- Returns:
A new instance containing remaining members
- Return type:
- Raises:
IncompatibleTypesError – If other is not a CombineEnums instance or Enum class
- format_debug()[source]
Comprehensive debug representation showing all internal state.
Returns a detailed multi-line string showing: - All enum classes - All members with their values - Value mappings - Statistics
- Return type:
- __radd__(other)
Add another CombineEnums instance or Enum class to this instance. Returns a new CombineEnums instance containing members from both operands.
- Parameters:
other (
Union[EnumRegistry,Type[Enum]]) – Another CombineEnums instance or Enum class- Returns:
A new instance containing combined members
- Return type:
- Raises:
IncompatibleTypesError – If other is not a CombineEnums instance or Enum class
- __rsub__(other)
Subtract another CombineEnums instance or Enum class from this instance. Returns a new CombineEnums instance containing members only from this instance.
- Parameters:
other (
Union[EnumRegistry,Type[Enum]]) – Another CombineEnums instance or Enum class- Returns:
A new instance containing remaining members
- Return type:
- Raises:
IncompatibleTypesError – If other is not a CombineEnums instance or Enum class
- __iadd__(other)[source]
Inplace addition.
- Return type:
- __isub__(other)[source]
Inplace subtraction.
- Return type:
DynamicEnum
- class true.enums_toolkits.DynamicEnum(**kwargs)[source]
Bases:
objectA dynamic enumeration class that allows runtime modification of members.
This class provides functionality to create and manage enum-like objects that can be modified during runtime, unlike traditional Python enums. It supports adding and removing members dynamically while maintaining the familiar enum interface.
- Variables:
_value2member_map_ (Dict[Any, Any]) – Mapping of values to enum members.
- __init__(**kwargs)[source]
- add_member(name, value)[source]
Adds a new member to the enumeration.
- Parameters:
name (str) – The name of the new enum member.
value (Any) – The value associated with the enum member.
- Raises:
ValueError – If the name is invalid or already exists.
- Return type:
- remove_member(name)[source]
Removes a member from the enumeration.
- Parameters:
name (str) – The name of the enum member to remove.
- Raises:
ValueError – If the member does not exist.
- Return type:
- property names: list
Returns a list of all member names.
- Returns:
List of member names.
- Return type:
- property values: list
Returns a list of all member values.
- Returns:
List of member values.
- Return type:
Collections and File System
File System Objects
- class true.collections.File(path, base_path=None)[source]
Bases:
FileSystemObjectEnhanced file class with additional capabilities
- __init__(path, base_path=None)[source]
- property filename: str
- property extension: str
- property size: int
- property md5: str
- property mime_type: str
Get file MIME type
- copy_to(destination, overwrite=False)[source]
Copy file to destination with retry mechanism
- Return type:
- class true.collections.Directory(path, base_path=None)[source]
Bases:
FileSystemObjectEnhanced directory class with additional capabilities
- __init__(path, base_path=None)[source]
- property size: int
Get cached directory size with automatic refresh
- zip_contents(output_path, compression=8)[source]
Create a zip archive of directory contents
- Return type:
- get_tree(max_depth=None)[source]
Get directory structure as a nested dictionary
- property is_empty: bool
Check if directory is empty
RecycleBin
- class true.collections.RecycleBin(location, max_size=1073741824)[source]
Bases:
AbstractRecycleBinAdvanced RecycleBin implementation with extensive features.
- __init__(location, max_size=1073741824)[source]
Initialize RecycleBin.
- delete(path)[source]
Move item to recycle bin.
- Parameters:
path (
str) – Path to item to be deleted- Returns:
Item ID in recycle bin
- Return type:
- Raises:
StorageFullError – If recycle bin is full
FileNotFoundError – If item doesn’t exist
- restore(item_id)[source]
Restore item from recycle bin.
- list_items(pattern=None)[source]
List items in recycle bin with optional pattern matching.
- batch_operation()[source]
Context manager for batch operations.
- async_batch_operation()[source]
Async context manager for batch operations.
- __enter__()[source]
Context manager entry.
- __exit__(exc_type, exc_val, exc_tb)[source]
Context manager exit.
- async __aenter__()[source]
Async context manager entry.
- async __aexit__(exc_type, exc_val, exc_tb)[source]
Async context manager exit.
OSUtils
- class true.collections.OSUtils(base_path=None, max_workers=4)[source]
Bases:
objectEnhanced OS utility class with comprehensive file system operations
- __init__(base_path=None, max_workers=4)[source]
- _setup_logging()[source]
Configure logging with rotation
- safe_move(src, dst, overwrite=False)[source]
Safely move a file or directory with retry mechanism
- Return type:
- batch_process(file_list, operation, parallel=True)[source]
Process multiple files in parallel or sequentially
- watch_directory(directory, callback)[source]
Watch a directory for changes and call callback on file events.
- stop_watching(directory=None)[source]
Stop watching a specific directory or all directories
- Return type:
- safe_delete(path, secure=False)[source]
Safely delete a file or directory with optional secure deletion.
- force_delete(path)[source]
Forcefully delete a file or directory, using extreme measures for both Unix and Windows.
- static _secure_delete_file(path, passes=3)[source]
Securely delete a file by overwriting its contents
- Return type:
- find_files_by_date(directory, start_date=None, end_date=None, modified=True)[source]
Find files within a date range.
- get_directory_stats(directory)[source]
Get comprehensive directory statistics
- export_operation_history(output_file)[source]
Export operation history to JSON file
- Return type:
- __enter__()[source]
Context manager entry
- __exit__(exc_type, exc_val, exc_tb)[source]
Context manager exit with cleanup
- __del__()[source]
Cleanup on deletion
Time Management
Time
- class true.time.Time(time_input=None, timezone_name=None, config=None)[source]
Bases:
objectAdvanced Time handling class with localization support and extended functionality.
- __init__(time_input=None, timezone_name=None, config=None)[source]
Initialize a Time object.
- property datetime: datetime
Get datetime object.
- property timezone: str
Get timezone name.
- property quarter: int
Get year quarter (1-4).
- is_between(start, end, inclusive=True)[source]
Check if time is between start and end times.
- Return type:
- with_timezone(timezone_name)[source]
Return new Time instance with different timezone.
- Return type:
- with_time(hour=0, minute=0, second=0, microsecond=0)[source]
Return new Time instance with specified time components.
- Return type:
- with_date(year=None, month=None, day=None)[source]
Return new Time instance with specified date components.
- Return type:
- static _parse_input(time_input)[source]
Parse various input formats to a datetime object.
- Return type:
- format(format_type=TimeFormat.HOUR_24, custom_format=None, locale_name=None)[source]
Format time according to specified format and locale.
- difference(other, unit=TimeUnit.SECONDS)[source]
Calculate time difference in specified unit.
- Return type:
- static get_available_timezones()[source]
Return list of available timezone names.
- _add_months(months)[source]
Helper method to calculate the timedelta for adding months.
- Return type:
- timer()[source]
A Timer context manager to calculate the time consumed inside a block of code.
- classmethod now(timezone_name=None)[source]
Get current time in specified timezone.
- Return type:
- __sub__(other)[source]
Subtract Time, timedelta, or seconds from Time instance.
- __le__(other)[source]
Compare less than or equal with another Time instance.
Event
- class true.time.Event(name, start_time, end_time, description=None, recurrence=None, tags=None, priority=0, metadata=None)[source]
Bases:
objectRepresents a scheduled event with comprehensive time management capabilities.
-
name:
str
-
start_time:
Time
-
end_time:
Time
-
priority:
int= 0
- __post_init__()[source]
Validate event data after initialization.
- get_next_occurrence()[source]
Get the next occurrence of a recurring event.
- __init__(name, start_time, end_time, description=None, recurrence=None, tags=None, priority=0, metadata=None)
-
name:
Schedule
- class true.time.Schedule(timezone_name=None)[source]
Bases:
objectAdvanced scheduling system with support for complex time-based operations.
Features: - Event management (add, remove, update) - Conflict detection and resolution - Recurring events support - Event filtering and searching - Schedule optimization - Time block allocation - Schedule statistics and analytics
- __init__(timezone_name=None)[source]
- add_event(event, check_conflicts=True)[source]
Add an event to the schedule with optional conflict checking.
- Return type:
- update_event(event_name, **kwargs)[source]
Update an existing event with new attributes.
- Return type:
- get_events(start, end, tags=None, priority_min=None)[source]
Get events within a time range with optional filtering.
- find_free_slots(start, end, duration, unit=TimeUnit.MINUTES)[source]
Find available time slots of specified duration.
- get_statistics(start, end)[source]
Calculate comprehensive schedule statistics for a time period.
- _find_conflicts(new_event)[source]
Find all events that conflict with a given event.
Regular Expressions
Username Patterns
- true.re.USERNAME_ONLY_LETTERS_MIN_3
- true.re.USERNAME_LETTERS_AND_NUMBERS_MIN_3
- true.re.USERNAME_WITH_UNDERSCORES_MIN_3
- true.re.USERNAME_WITH_DASHES_AND_UNDERSCORES_MIN_3
- true.re.USERNAME_NO_CONSECUTIVE_SPECIAL_CHARS
- true.re.USERNAME_STARTS_WITH_LETTER
- true.re.USERNAME_MAX_20_CHARACTERS
- true.re.USERNAME_NOT_NUMERIC_ONLY
- true.re.USERNAME_NO_PREFIX_SUFFIX
- true.re.USERNAME_INCLUDE_LETTER_AND_NUMBER
Password Patterns
- true.re.PASSWORD_MIN_8
- true.re.PASSWORD_MIN_8_WITH_NUMBER
- true.re.PASSWORD_MIN_8_UPPER_LOWER_NUMBER
- true.re.PASSWORD_MIN_8_UPPER_LOWER_NUMBER_SPECIAL
- true.re.PASSWORD_NO_WHITESPACE
Email Patterns
- true.re.EMAIL_BASIC
- true.re.EMAIL_RFC_5322
- true.re.EMAIL_WITH_SUBDOMAINS
- true.re.EMAIL_WITH_UNICODE
Type System
Version Types
- class true.types.Version(major, minor, patch=None, tag=None)[source]
Bases:
object-
major:
str
-
minor:
str
-
PATTERNS:
ClassVar[set] = {'^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$', '^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$', '^(19|20)\\d\\d\\.(0[1-9]|1[0-2])\\.(0[1-9]|[12][0-9]|3[01])$', '^(19|20)\\d\\d\\.(0[1-9]|[1-4][0-9]|5[0-3])$'}
- property version: str
- __init__(major, minor, patch=None, tag=None)
-
major:
- class true.types.SemVersion(major, minor, patch=None, tag=None)[source]
Bases:
VersionValidatorMixin,Version- PATTERN = '^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$'
- class true.types.CalVersion(major, minor, patch=None, tag=None)[source]
Bases:
VersionValidatorMixin,Version- PATTERN = '^(19|20)\\d\\d\\.(0[1-9]|[1-4][0-9]|5[0-3])$'
Numeric Types
- class true.types.BigInt(value: int, strict: bool = False, context: Literal['Positive', 'Negative', 'Unsigned'] = 'Positive')[source]
Bases:
int- arch = '64bit'
- class true.types.BigDecimal(value: float | Decimal | Infinity | NaN, strict: bool = False, context: Literal['Positive', 'Negative', 'Unsigned'] = 'Positive', stop_warnings: bool = False)[source]
Bases:
Decimal- classmethod _create_decimal(value)[source]
Convert input value to Decimal.
- Return type:
BigDecimal
- static _convert_to_float(decimal_value)[source]
Convert Decimal to float for range checking.
- Return type:
- classmethod _validate_strict_mode(float_value, decimal_value, stop_warnings)[source]
Validate value against float limits in strict mode.
- Return type:
- classmethod _check_float_limits(abs_float_value, decimal_value)[source]
Check if value exceeds float limits.
- Return type:
- classmethod _check_boundary_conditions(abs_float_value, decimal_value, stop_warnings)[source]
Check and warn for boundary conditions.
- Return type:
- class true.types.ScientificNumber(value: str)[source]
Bases:
str- static __new__(cls, value)[source]
Scientific Number representation.
Consists of: - Coefficient (Mantissa): Significant figure (whole or decimal). - Exponent: Denoted by ‘e’ or ‘E’, with sign and integer. - Decimal: Part of coefficient, indicates precise value placement.
- Parameters:
value (
str) – String representation of the scientific number.
ID Types
- class true.types.UUIDType(value)[source]
Bases:
ABC- classmethod _convert_value(value)[source]
Convert the value to the appropriate type (str or int).
- classmethod _validate_length(value)[source]
Validate the length of the input value.
- classmethod _create_uuid(value)[source]
Create a UUID instance based on the input value.
- Return type:
Type[UUIDType]
- classmethod _validate_version(uuid_obj)[source]
Optionally validate the UUID version.
Exceptions
Enum Exceptions
- exception true.exceptions.InvalidEnumTypeError[source]
Raised when an invalid enum type is provided.
- exception true.exceptions.EnumMetadataError[source]
Custom exception for enum metadata-related errors.
- exception true.exceptions.EnumValidationError[source]
Custom error for invalid enum values.
File System Exceptions
- exception true.exceptions.StorageFullError[source]
Raised when recycle bin storage limit is exceeded.
- exception true.exceptions.RecycleBinError[source]
Base exception for RecycleBin operations.
- exception true.exceptions.ItemNotFoundError[source]
Raised when an item is not found in the recycle bin.
- exception true.exceptions.RestoreError[source]
Raised when item restoration fails.
Type Exceptions
- exception true.exceptions.UnsuitableBigIntError[source]
Raised when an integer value is unsuitable.
- exception true.exceptions.UnsuitableBigDecimalError[source]
Raised when a decimal value is unsuitable.
- exception true.exceptions.InvalidUUIDError[source]
Exception raised for invalid UUIDs.
- exception true.exceptions.InvalidUUIDVersionError[source]
Exception raised when a UUID does not match the expected version.
- exception true.exceptions.InvalidULIDError[source]
Exception raised for invalid ULIDs.
Time Exceptions
- exception true.exceptions.ScheduleError[source]
Base exception for schedule-related errors.
- exception true.exceptions.ScheduleConflictError[source]
Raised when there is a conflict between scheduled events.
- exception true.exceptions.ScheduleValidationError[source]
Raised when schedule validation fails.