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 enum_classes: Set[Type[Enum]]

Get set of registered enum classes

property metadata: EnumMetadata

Returns the metadata associated with the enum registry.

_initialize_members(allow_duplicates)[source]

Initialize internal member mappings

Return type:

None

register(enums)[source]

Register new enums to the registry.

Return type:

EnumRegistry

deregister(enums)[source]

Deregister enums from the registry.

Return type:

EnumRegistry

dregister(enum_class=None)[source]

Decorator to register an enum class.

get_enum_metadata(member)[source]

Get metadata for an enum member

Return type:

Dict[str, Any]

members_of(enum_class)[source]

Get all enum members from a specific enum class.

Return type:

List[Enum]

set_member_metadata(member, **kwargs)[source]

Set metadata for an enum member

Return type:

None

get_member_metadata(member)[source]

Get metadata for an enum member

Return type:

Dict[str, Any]

_create_filtered_instance(members)[source]

Helper method to create new instance from filtered members.

Return type:

EnumRegistry

to_dict()[source]

Convert registry to dictionary format

Return type:

Dict[str, List[EnumData]]

statistics()[source]

Get comprehensive statistics about the registry :returns: An EnumStats dataclass instance :rtype: EnumStats

members()[source]

Group members by their original enum class.

Return type:

Dict[Type[Enum], List[Enum]]

merge(*combine_enums)[source]

Merge multiple CombineEnums instances into a new instance.

Return type:

EnumRegistry

__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:

EnumRegistry

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:

EnumRegistry

Raises:

IncompatibleTypesError – If other is not a CombineEnums instance or Enum class

static is_enum(other)[source]
Return type:

bool

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:

str

__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:

EnumRegistry

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:

EnumRegistry

Raises:

IncompatibleTypesError – If other is not a CombineEnums instance or Enum class

__iadd__(other)[source]

Inplace addition.

Return type:

EnumRegistry

__isub__(other)[source]

Inplace subtraction.

Return type:

EnumRegistry

__iter__()[source]

Iterate over all enum members.

Return type:

Iterator[Enum]

__next__()[source]

Get the next enum member.

Return type:

Enum

__hash__()[source]

Generate hash based on enum members.

Return type:

int

__eq__(other)[source]

Compare equality with another CombineEnums instance.

Return type:

bool

__lt__(other)[source]

Compare less than with another CombineEnums instance.

Return type:

bool

__contains__(item)[source]

Check if an item exists in the combined enums. Supports checking by name, enum member, or value.

Return type:

bool

DynamicEnum

class true.enums_toolkits.DynamicEnum(**kwargs)[source]

Bases: object

A 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:

None

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:

None

property names: list

Returns a list of all member names.

Returns:

List of member names.

Return type:

list

property values: list

Returns a list of all member values.

Returns:

List of member values.

Return type:

list

classmethod from_enum(enum_class)[source]

Creates a DynamicEnum from an existing Enum class.

Parameters:

enum_class (type[Enum]) – The source Enum class to convert.

Returns:

A new DynamicEnum instance with members from the source Enum.

Return type:

DynamicEnum

Collections and File System

File System Objects

class true.collections.File(path, base_path=None)[source]

Bases: FileSystemObject

Enhanced 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

get_stats()[source]

Get comprehensive file statistics

Return type:

FileStats

copy_to(destination, overwrite=False)[source]

Copy file to destination with retry mechanism

Return type:

bool

create_backup(suffix='.bak')[source]

Create a backup copy of the file

Return type:

File

is_text_file()[source]

Check if file is a text file

Return type:

bool

read_text(encoding='utf-8')[source]

Read text file content

Return type:

str

write_text(content, encoding='utf-8')[source]

Write text to file

Return type:

int

class true.collections.Directory(path, base_path=None)[source]

Bases: FileSystemObject

Enhanced directory class with additional capabilities

__init__(path, base_path=None)[source]
property size: int

Get cached directory size with automatic refresh

_calculate_size()[source]

Calculate total directory size

Return type:

int

glob(pattern)[source]
Return type:

Generator[Path, None, None]

rglob(pattern)[source]
Return type:

Generator[Path, None, None]

create(exist_ok=True)[source]

Create directory if it doesn’t exist

Return type:

bool

zip_contents(output_path, compression=8)[source]

Create a zip archive of directory contents

Return type:

bool

get_tree(max_depth=None)[source]

Get directory structure as a nested dictionary

Return type:

Dict[str, Any]

property is_empty: bool

Check if directory is empty

delete()[source]

Delete directory and its contents

Return type:

None

RecycleBin

class true.collections.RecycleBin(location, max_size=1073741824)[source]

Bases: AbstractRecycleBin

Advanced RecycleBin implementation with extensive features.

__init__(location, max_size=1073741824)[source]

Initialize RecycleBin.

Parameters:
  • location (str) – Base directory for the recycle bin

  • max_size (int) – Maximum size in bytes (default 1GB)

_setup()[source]

Initialize recycle bin directory structure.

Return type:

None

_load_metadata()[source]

Load metadata from disk.

Return type:

None

_save_metadata()[source]

Save metadata to disk.

Return type:

None

get_total_size()[source]

Get total size of items in recycle bin.

Return type:

int

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:

str

Raises:
  • StorageFullError – If recycle bin is full

  • FileNotFoundError – If item doesn’t exist

async async_delete(path)[source]

Asynchronous version of delete operation.

Return type:

str

restore(item_id)[source]

Restore item from recycle bin.

Parameters:

item_id (str) – ID of item to restore

Raises:
  • ItemNotFoundError – If item not found in recycle bin

  • RestoreError – If restoration fails

Return type:

None

async async_restore(item_id)[source]

Asynchronous version of restore operation.

Return type:

None

static _calculate_checksum(path)[source]

Calculate file checksum.

Return type:

str

list_items(pattern=None)[source]

List items in recycle bin with optional pattern matching.

Return type:

Generator[FileMetadata, None, None]

add_tag(item_id, tag)[source]

Add tag to item.

Return type:

None

remove_tag(item_id, tag)[source]

Remove tag from item.

Return type:

None

cleanup(days=30)[source]

Remove items older than specified days.

Return type:

None

_permanent_delete(item_id)[source]

Permanently delete item from recycle bin.

Return type:

None

_start_job_handler()[source]

Start background job handler thread.

Return type:

None

batch_operation()[source]

Context manager for batch operations.

async_batch_operation()[source]

Async context manager for batch operations.

__str__()[source]

String representation.

Return type:

str

__repr__()[source]

Detailed string representation.

Return type:

str

__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: object

Enhanced OS utility class with comprehensive file system operations

__init__(base_path=None, max_workers=4)[source]
_setup_logging()[source]

Configure logging with rotation

get_file(path)[source]
Return type:

File

get_directory(path)[source]
Return type:

Directory

safe_move(src, dst, overwrite=False)[source]

Safely move a file or directory with retry mechanism

Return type:

bool

batch_process(file_list, operation, parallel=True)[source]

Process multiple files in parallel or sequentially

Return type:

Dict[str, bool]

watch_directory(directory, callback)[source]

Watch a directory for changes and call callback on file events.

Parameters:
  • directory (str) – Directory path to watch

  • callback (callable) – Function to call when changes occur

Return type:

None

stop_watching(directory=None)[source]

Stop watching a specific directory or all directories

Return type:

None

safe_delete(path, secure=False)[source]

Safely delete a file or directory with optional secure deletion.

Parameters:
  • path (str) – Path to delete

  • secure (bool) – If True, overwrite file contents before deletion

Return type:

bool

force_delete(path)[source]

Forcefully delete a file or directory, using extreme measures for both Unix and Windows.

Parameters:

path (str) – Path to delete

Returns:

True if deletion was successful, False otherwise

Return type:

bool

static _secure_delete_file(path, passes=3)[source]

Securely delete a file by overwriting its contents

Return type:

None

find_files_by_date(directory, start_date=None, end_date=None, modified=True)[source]

Find files within a date range.

Parameters:
  • directory (str) – Directory to search

  • start_date (datetime) – Start date for search

  • end_date (datetime) – End date for search

  • modified (bool) – If True, use modification date, else creation date

Return type:

List[str]

get_directory_stats(directory)[source]

Get comprehensive directory statistics

Return type:

Dict[str, Any]

_log_operation(operation_type, details)[source]

Log operation with timestamp

Return type:

None

export_operation_history(output_file)[source]

Export operation history to JSON file

Return type:

bool

__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: object

Advanced Time handling class with localization support and extended functionality.

__init__(time_input=None, timezone_name=None, config=None)[source]

Initialize a Time object.

Parameters:
property datetime: datetime

Get datetime object.

property timezone: str

Get timezone name.

property quarter: int

Get year quarter (1-4).

floor(unit)[source]

Floor time to the nearest unit.

Return type:

Time

ceil(unit)[source]

Ceil time to the nearest unit.

Return type:

Time

round(unit)[source]

Round time to the nearest unit.

Return type:

Time

start_of(unit)[source]

Get start of time unit (alias for a floor).

Return type:

Time

end_of(unit)[source]

Get end-of-time unit.

Return type:

Time

is_between(start, end, inclusive=True)[source]

Check if time is between start and end times.

Return type:

bool

is_same(other, unit)[source]

Check if two times are in the same time unit.

Return type:

bool

classmethod min(*times)[source]

Get the earliest time from a sequence.

Return type:

Time

classmethod max(*times)[source]

Get the latest time from a sequence.

Return type:

Time

with_timezone(timezone_name)[source]

Return new Time instance with different timezone.

Return type:

Time

with_time(hour=0, minute=0, second=0, microsecond=0)[source]

Return new Time instance with specified time components.

Return type:

Time

with_date(year=None, month=None, day=None)[source]

Return new Time instance with specified date components.

Return type:

Time

static _parse_input(time_input)[source]

Parse various input formats to a datetime object.

Return type:

datetime

to_timezone(timezone_name)[source]

Convert time to different timezone.

Return type:

Time

format(format_type=TimeFormat.HOUR_24, custom_format=None, locale_name=None)[source]

Format time according to specified format and locale.

Parameters:
  • format_type (TimeFormat) – TimeFormat enum value

  • custom_format (Optional[str]) – Custom strftime format string

  • locale_name (Optional[str]) – Locale name (e.g., ‘en_US’)

Return type:

str

difference(other, unit=TimeUnit.SECONDS)[source]

Calculate time difference in specified unit.

Return type:

float

static get_available_timezones()[source]

Return list of available timezone names.

Return type:

List[str]

add(amount, unit)[source]

Add time duration to current time.

Return type:

Time

_add_months(months)[source]

Helper method to calculate the timedelta for adding months.

Return type:

timedelta

is_dst()[source]

Check if the current time is in DST.

Return type:

bool

to_dict()[source]

Convert a time object to dictionary representation.

Return type:

Dict

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:

Time

__str__()[source]

String representation of a time object.

Return type:

str

__repr__()[source]

Detailed string representation of a time object.

Return type:

str

__add__(other)[source]

Add timedelta or seconds to Time instance.

Return type:

Time

__sub__(other)[source]

Subtract Time, timedelta, or seconds from Time instance.

Return type:

Union[Time, timedelta]

__eq__(other)[source]

Compare equality with another Time instance.

Return type:

bool

__lt__(other)[source]

Compare less than with another Time instance.

Return type:

bool

__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: object

Represents a scheduled event with comprehensive time management capabilities.

name: str
start_time: Time
end_time: Time
description: Optional[str] = None
recurrence: Optional[str] = None
tags: List[str] = None
priority: int = 0
metadata: Dict[str, Any] = None
__post_init__()[source]

Validate event data after initialization.

overlaps(other)[source]

Check if this event overlaps with another event.

Return type:

bool

duration(unit=TimeUnit.MINUTES)[source]

Get event duration in specified unit.

Return type:

float

is_recurring()[source]

Check if the event is recurring.

Return type:

bool

get_next_occurrence()[source]

Get the next occurrence of a recurring event.

Return type:

Optional[Event]

__init__(name, start_time, end_time, description=None, recurrence=None, tags=None, priority=0, metadata=None)

Schedule

class true.time.Schedule(timezone_name=None)[source]

Bases: object

Advanced 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:

None

remove_event(event_name)[source]

Remove an event by name.

Return type:

Event

update_event(event_name, **kwargs)[source]

Update an existing event with new attributes.

Return type:

Event

get_events(start, end, tags=None, priority_min=None)[source]

Get events within a time range with optional filtering.

Return type:

List[Event]

find_free_slots(start, end, duration, unit=TimeUnit.MINUTES)[source]

Find available time slots of specified duration.

Return type:

List[Time]

get_statistics(start, end)[source]

Calculate comprehensive schedule statistics for a time period.

Return type:

Dict[str, Any]

_find_conflicts(new_event)[source]

Find all events that conflict with a given event.

Return type:

List[Event]

static _calculate_tags_distribution(events)[source]

Calculate the distribution of tags across events.

Return type:

Dict[str, int]

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
patch: Optional[str] = None
tag: Optional[str] = None
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)
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:

float

classmethod _validate_strict_mode(float_value, decimal_value, stop_warnings)[source]

Validate value against float limits in strict mode.

Return type:

None

classmethod _check_float_limits(abs_float_value, decimal_value)[source]

Check if value exceeds float limits.

Return type:

None

classmethod _check_boundary_conditions(abs_float_value, decimal_value, stop_warnings)[source]

Check and warn for boundary conditions.

Return type:

None

static _validate_context(float_value, decimal_value, context)[source]

Validate value against specified context.

Return type:

None

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).

Return type:

Union[str, int, NoReturn]

classmethod _validate_length(value)[source]

Validate the length of the input value.

Return type:

Union[str, int]

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.

class true.types.ULIDType[source]

Bases: ABC

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.

exception true.exceptions.EnumTypeError(expected_type, actual_type)[source]

Custom error for type mismatches in enum.

__init__(expected_type, actual_type)[source]

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.