-
Notifications
You must be signed in to change notification settings - Fork 0
aplustools.package
TBA
class aplustools.package.autocli.ArgStructBuilder
Bases:
objectA utility class for constructing and managing a hierarchical argument structure.
ArgStructBuilder allows users to build a nested dictionary structure that represents CLI commands and their subcommands. The resulting structure can be used in CLI parsers or for other command-line interfaces.
_commandsThe command structure dictionary, storing commands and subcommands with their respective mappings.
Type: dict __init__() -> None
add_command(command: str, subcommands: dict | None = None) -> None
Adds a top-level command with optional subcommands.
Parameters:
- command (str) – The main command to add to the structure.
- subcommands (Optional**[**dict*]**, **optional*) – Dictionary of subcommands, if applicable. If not provided, an empty dictionary is assigned.
add_nested_command(parent: str, command: str, subcommand: str | dict | None) -> None
Adds a nested command within a command structure hierarchy.
Navigates to the specified parent path in the command structure, allowing creation of complex, multi-level command hierarchies.
Parameters:
- parent (str) – Dot-separated string representing the parent command path.
- command (str) – The command to add within the specified parent path.
- subcommand (Optional**[**str* | dict]*) – Structure for the subcommand. If None, an empty dictionary is used.
Raises: ValueError – If the specified parent path is not valid.
add_subcommand(parent: str, subcommand: str) -> None
Adds a subcommand under an existing top-level command.
If the parent command does not exist, raises a ValueError.
Parameters:
- parent (str) – The parent command under which to add the subcommand.
- subcommand (str) – The subcommand to add within the parent command.
Raises: ValueError – If the parent command does not exist or is incompatible with having subcommands.
get_structure() -> dict[str, dict | str]
Retrieves the full command structure dictionary.
Returns: The dictionary representing all commands and subcommands, which can be used directly by other classes or modules for parsing. Return type: dict
exception aplustools.package.autocli.ArgumentParsingError(message: str, index: int)
Bases:
ExceptionException raised when an error occurs during argument parsing.
This exception is used to indicate issues when parsing command-line arguments. It includes a message and an index to indicate where the error occurred, helping users or developers identify the issue in the input command.
indexThe position in the argument list where the error was detected.
Type: int __init__(message: str, index: int) -> None
class aplustools.package.autocli.Argumint(default_endpoint: EndPoint, arg_struct: dict[str, dict | str])
Bases:
objectA command-line argument parser that uses structured arguments and endpoints.
Argumint is designed to parse CLI arguments using a predefined argument structure. It allows users to define and manage argument paths, replace the argument structure, and execute endpoints based on parsed arguments.
default_endpointThe default endpoint to call if a path cannot be resolved.
Type: EndPoint
_arg_structThe dictionary representing the current argument structure.
Type: dict
_endpointsA mapping of argument paths to endpoint functions.
Type: dict __init__(default_endpoint: EndPoint, arg_struct: dict[str, dict | str]) -> None
add_endpoint(path: str, endpoint: EndPoint) -> None
Adds an endpoint at a specified path within the structure.
The endpoint will be callable from the CLI if the provided path matches.
Parameters:
- path (str) – Dot-separated path where the endpoint will be added.
- endpoint (EndPoint) – The endpoint instance to associate with the path.
Raises: ValueError – If the path does not exist within the argument structure or if it already has an endpoint assigned.
parse_cli(system: <module 'sys' (built-in)> = <module 'sys' (built-in)>, mode: ~typing.Literal['arg_parse', 'native_light'] = 'arg_parse') -> None
Parses CLI arguments and calls the endpoint based on the parsed path.
This method processes command-line input, navigates the argument structure, and calls the relevant endpoint function. If the path is unmatched, it calls the default_endpoint.
Parameters: replace_arg_struct(new_arg_struct: dict) -> None
Replaces the current argument structure with a new one.
Updates the structure and removes any existing endpoints that do not match the new structure.
Parameters: new_arg_struct (dict) – The new argument structure to replace the current one. replace_endpoint(path: str, endpoint: EndPoint) -> None
Replaces an existing endpoint at a given path.
This method checks if the specified path exists in the argument structure before replacing the existing endpoint with the new one. If the path does not exist, an error is raised.
Parameters:
- path (str) – The path where the endpoint will be replaced.
- endpoint (EndPoint) – The new endpoint to assign to the specified path.
Raises: ValueError – If the specified path does not exist in the argument structure.
class aplustools.package.autocli.EndPoint(function: LambdaType)
Bases:
objectRepresents the endpoint of a trace from an argument structure object.
The EndPoint class serves as a container for functions associated with a particular argument path, providing a way to call the function with predefined arguments and keyword arguments.
analysisDictionary containing analysis data of the function’s arguments, such as names and types, generated by analyze_function.
Type: dict
_arg_indexA mapping of argument names to their indices, allowing quick lookup of argument positions by name.
Type: dict
_functionThe actual function associated with this endpoint, which will be called when the endpoint is invoked.
Type: _ts.FunctionType __init__(function: LambdaType) -> None
call(*args, **kwargs) -> None
Executes the internal function using the specified arguments.
This method forwards all positional and keyword arguments to the stored function, allowing flexible invocation from various contexts.
Parameters:
- *args – Positional arguments to pass to the function.
- **kwargs – Keyword arguments to pass to the function.
class aplustools.package.autocli.NoDefault
Bases: object
aplustools.package.autocli.analyze_function(function: Callable) -> dict[str, list[Any] | str | None]
Analyzes a given function’s signature and docstring, returning a structured summary of its arguments, including default values, types, keyword-only flags, documentation hints, and choices for Literal-type arguments. Also extracts information on **args*, **kwargs, and the return type.
Parameters: function (types.FunctionType) – The function to analyze.
Returns:
- A dictionary containing the following keys:
”name” (str): The name of the function.
”doc” (str): The function’s docstring.
”arguments” (List[Dict[str, Union[str, None]]]): Details of each argument:
- ”name” (str): The argument’s name.
- ”default” (Any or None): The default value, if provided.
- ”choices” (List[Any] or []): Options for Literal type hints, if applicable.
- ”type” (Any or None): The argument’s type hint.
- ”doc_help” (str): The extracted docstring help for the argument.
- ”kwarg_only” (bool): True if the argument is keyword-only.
”has_*args” (bool): True if the function accepts variable positional arguments.
”has_**kwargs” (bool): True if the function accepts variable keyword arguments.
”return_type” (Any or None): The function’s return type hint.
”return_choices” (List[Any] or []): Options for Literal type hints for the return type, if applicable.
”return_doc_help” (str): The extracted docstring help for the return type.
Return type: dict
This module provides a collection of timing utilities, including timers with different resolution levels, time formatting and conversion utilities, and performance measurement tools for function execution time analysis.
class aplustools.package.chronokit.BasicTimer(auto_start: bool = False)
Bases:
objectA class to represent a basic timer that can be started, stopped, paused, resumed, and records tick-tock intervals. It also supports tallying recorded time intervals, calculating the average duration, and converting elapsed time to a readable format.
start_timeThe timestamp when the timer started.
Type: float or None
stop_timeThe timestamp when the timer stopped.
Type: float or None
pause_start_timeThe timestamp when the timer was paused.
Type: float or None
pause_durationThe total duration the timer has been paused.
Type: float
tick_tocksA list of tuples containing the start and stop times for each tick-tock interval.
Type: list of tuples
is_stoppedA flag indicating whether the timer is currently stopped.
Type: bool
is_endedA flag indicating whether the timer has ended.
Type: bool
Parameters: auto_start (bool) – If True, starts the timer automatically upon initialization. __init__(auto_start: bool = False) -> None
Initializes the BasicTimer object. Optionally starts the timer immediately.
Parameters: auto_start (bool) – If True, the timer starts automatically upon initialization. average() -> timedelta | None
Calculates the average duration of all recorded tick-tock intervals.
Returns: The average duration as a timedelta object, or None if no intervals are recorded. Return type: timedelta or None end() -> Self
Ends the timer, preventing any further operations such as start, pause, or resume.
Returns: The current BasicTimer instance for method chaining. Return type: self get() -> timedelta | None
Retrieves the current elapsed time from when the timer was started. If the timer is paused or stopped, it calculates the time up to that point.
Returns: The total elapsed time as a timedelta object, or None if the timer has not been started. Return type: timedelta or None get_readable(format_to: PreciseTimeFormat = PreciseTimeFormat.SECONDS) -> str
Converts the current elapsed time to a human-readable format based on the specified time unit.
Parameters: format_to (int) – The time format to convert to. Defaults to TimeFormat.SECONDS. Returns: A human-readable string representing the elapsed time in the specified format. Return type: str get_times() -> list[tuple[float, float]]
Retrieves the list of all tick-tock intervals recorded.
Returns: Each tuple contains the start and stop times for each tick-tock interval. Return type: list of tuples pause() -> Self
Pauses the timer, storing the current time as the pause start time. Raises an error if the timer is already paused, stopped, or not started.
Returns: The current BasicTimer instance for method chaining. Return type: self resume() -> Self
Resumes the timer from a paused state and adjusts the total paused duration. Raises an error if the timer is not paused or has ended.
Returns: The current BasicTimer instance for method chaining. Return type: self split_end() -> Self
Records a tock, which captures the current time as an interval end. Raises an error if the timer has ended or is not started.
Returns: The current BasicTimer instance for method chaining. Return type: self split_start() -> Self
Records a tick, which captures the current time as an interval start. Raises an error if the timer has ended or is not started.
Returns: The current BasicTimer instance for method chaining. Return type: self start() -> Self
Starts the timer. If the timer was stopped or paused, it resets the start time and resumes recording. Raises an error if the timer has already been started or ended.
Returns: The current BasicTimer instance for method chaining. Return type: self stop() -> Self
Stops the timer and records the current time as the stop time. Raises an error if the timer is already stopped or not started.
Returns: The current BasicTimer instance for method chaining. Return type: self tally() -> int | float
Calculates the total time recorded between all tick-tock intervals.
Returns: The total elapsed time in seconds. Return type: float
class aplustools.package.chronokit.CPUFTimer(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.CPUFTimerNS(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.DateTimeFTimer(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
This is a joke and should not be taken seriously as it isn’t performant.
class aplustools.package.chronokit.FlexTimer(start_at: int | float = 0, start_now: bool = True)
Bases:
objectA timer class to manage multiple timers and track elapsed time with nanosecond precision. If a time value is not specified as something specific, it is assumed to be in seconds.
EMPTYA constant tuple representing an empty timer slot.
Type: tuple
EMPTY: tuple[int | float, int | float, int | float, allocate_lock | None] = (0, 0, 0, None)
SENTINEL = <object object>__init__(start_at: int | float = 0, start_now: bool = True) -> None
Initializes the TimidTimer instance.
Parameters: after(delay: float | int, callback: Callable[[...], Any], *, ms: bool = False, long: bool = False, args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None) -> Self
Starts a countdown timer for a specified number of seconds. :param delay: The duration of the countdown in seconds. :param callback: The function to call when the countdown ends. Defaults to print. :param ms: Flag that determines if the delay param should be treated as seconds or milliseconds. :param long: Flag that determines if the timer should be optimized for long wait times. :param args: The arguments for the callback function. Defaults to a message with the countdown time. :param kwargs: The keyword arguments for the callback function. Defaults to None. :return:classmethod at(index: int, *args: Any, **kwargs: Any) -> Self
Retrieves or creates a timer object at the specified index.
This method ensures that you can access or create a timer object at any index in the _tracked_timers list without having to pass a direct reference. If the index is beyond the current length of _tracked_timers, the list is extended to accommodate the new index.
Parameters: index (int) – The index of the timer to access or create. Returns: The timer object at the specified index. Return type: _te.Self average(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta'] = 'PreciseTimeDelta') -> `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta
Calculates the average time recorded across all ticks and tocks.
Parameters: Returns: The average elapsed time across all ticks and tocks.
Return type: PreciseTimeDelta | timedelta
classmethod complexity(func: Callable, input_generator: Iterable[tuple[tuple[Any, ...], dict[str, Any]]] | Generator[tuple[tuple[Any, ...], dict[str, Any]], None, None], matplotlib_pyplt: ModuleType | None = None) -> str
Measures the execution time of a function over a range of input sizes and estimates the time complexity. Too little data points will lead to bigger error rates. Around 100 data points is the sweet spot. The first argument/keyword argument you pass (in the generator) will be used as the x so you need to enable int conversion for that class.
Parameters: func (Callable): The function to measure. input_generator (Iterable): A generator that yields increasing input sizes (e.g., range). matplotlib_pyplt: The pyplot class from the matplotlib library.
Returns: str: Estimated time complexity (e.g., “O(N)”, “O(N^2)”, etc.).
delete(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta', None] = 'PreciseTimeDelta') -> list[`PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta] | `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta | Self
Deletes the timer at the specified indices.
Parameters: Returns: The elapsed time(s) or TimidTimer: The current instance of the timer.
Return type: list[PreciseTimeDelta | timedelta] | PreciseTimeDelta | timedelta
elapsed(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta', None] = 'PreciseTimeDelta') -> list[`PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta] | `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta | Self
Records how much time has passed since the start of the timer (similar to elapsed).
Parameters: Returns: The elapsed time(s) or TimidTimer: The current instance of the timer.
Return type: list[PreciseTimeDelta | timedelta] | PreciseTimeDelta | timedelta
end(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta', None] = 'PreciseTimeDelta') -> list[`PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta] | `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta | Self
Ends the timer at the specified indices.
Parameters: Returns: The elapsed time(s) or TimidTimer: The current instance of the timer.
Return type: list[PreciseTimeDelta | timedelta] | PreciseTimeDelta | timedelta
enter(index: int | None = None) -> Self
Starts the timer and sets the index for thread-local storage when using the timer in a context manager.
Parameters: index (int*, **optional*) – The index of the timer to start. Defaults to None. Returns: The current instance of the timer. Return type: FlexTimer classmethod from_(index: int) -> Self
Retrieves the timer object at the specified index, if it exists.
This method attempts to access an existing timer at the specified index in the _tracked_timers list. If no timer exists at the given index, it raises an IndexError.
Parameters: index (int) – The index of the timer to retrieve. Returns: The timer object at the specified index. Return type: _te.Self Raises: IndexError – If no timer exists at the given index. get(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta'] = 'PreciseTimeDelta') -> list[`PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta] | `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta
Retrieves the elapsed time for the specified indices.
Parameters: Returns: The elapsed time(s).
Return type: list[PreciseTimeDelta | timedelta] | PreciseTimeDelta | timedelta
get_readable(index: int | None = None, format_to: PreciseTimeFormat = PreciseTimeFormat.SECONDS) -> str
Returns a readable string of the timer’s elapsed time.
Parameters: Returns: A human-readable string of the elapsed time.
Return type: str
interval(interval: float | int, count: int | Literal['inf'], callback: Callable[[...], Any], *, ms: bool = False, long: bool = False, args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None) -> Self
Starts an interval timer that triggers the callback at specified intervals. :param interval: The interval in seconds between each callback trigger. :param count: The number of times to trigger the callback. Defaults to “inf” (infinite). :param callback: The function to call at each interval. Defaults to print. :param ms: Flag that determines if the interval param should be treated as seconds or milliseconds. :param long: Flag that determines if the timer should be optimized for long wait times. :param args: The arguments for the callback function. Defaults to a message with the interval time. :param kwargs: The keyword arguments for the callback function. Defaults to None. :return:lap(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta', None] = 'PreciseTimeDelta') -> list[`PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta] | `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta | Self
Records the time between the last tock and the current tock (similar to lap or split time).
Parameters: Returns: The elapsed time(s) or TimidTimer: The current instance of the timer.
Return type: list[PreciseTimeDelta | timedelta] | PreciseTimeDelta | timedelta
load_state(state_bytes: bytes) -> None
Loads a previously saved state for all timers (excluding threads).
Parameters: state_bytes (bytes) – The serialized state to load. static load_state_static(state_bytes: bytes) -> `FlexTimer <#aplustools.package.chronokit.FlexTimer>`_
Loads a previously saved state for all timers (excluding threads).
Parameters: state_bytes (bytes) – The serialized state to load. loop(interval: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, index: int | None = None, daemon: bool = False) -> Self
Starts a repeating timer that triggers the specified function at set intervals indefinitely.
Parameters:
- interval (float* or **int*) – The interval between each execution, in seconds.
- function (Callable) – The function to execute at each interval.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- index (int*, **optional*) – The index for the timer in the internal list. Defaults to None (appends a new timer).
- daemon (bool*, **optional*) – Whether to run the timer thread as a daemon. Defaults to False.
Returns: The current instance of the timer.
Return type: loop_long(interval: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, index: int | None = None) -> Self
Starts a long-running repeating timer that triggers the specified function at set intervals indefinitely.
Parameters:
- interval (float* or **int*) – The interval between each execution, in seconds.
- function (Callable) – The function to execute at each interval.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- index (int*, **optional*) – The index for the timer in the internal list. Defaults to None (appends a new timer).
Returns: The current instance of the timer.
Return type: loop_ms(interval_ms: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, index: int | None = None, daemon: bool = False) -> Self
Starts a repeating timer that triggers the specified function at set intervals in milliseconds indefinitely.
Parameters:
- interval_ms (float* or **int*) – The interval between each execution, in milliseconds.
- function (Callable) – The function to execute at each interval.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- index (int*, **optional*) – The index for the timer in the internal list. Defaults to None (appends a new timer).
- daemon (bool*, **optional*) – Whether to run the timer thread as a daemon. Defaults to False.
Returns: The current instance of the timer.
Return type: pause(*indices: int | None, for_seconds: int | float | None = None) -> Self
Pauses the timer at the specified indices.
Parameters: Returns: The current instance of the timer.
Return type: classmethod repeat(interval: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, iterations: int = 1, daemon: bool = False) -> Type[Self]
Repeatedly triggers a function at a specified interval for a set number of iterations.
Parameters:
- interval (float* or **int*) – The time interval between each execution, in seconds.
- function (Callable) – The function to execute at each interval.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- iterations (int*, **optional*) – The number of times to execute the function. Defaults to 1.
- daemon (bool*, **optional*) – Whether to run the timer thread as a daemon. Defaults to False.
Returns: The class itself.
Return type: classmethod repeat_long(interval: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, iterations: int = 1) -> Type[Self]
Repeatedly triggers a function at a specified interval for a long-running timer, for a set number of iterations.
Parameters:
- interval (float* or **int*) – The time interval between each execution, in seconds.
- function (Callable) – The function to execute at each interval.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- iterations (int*, **optional*) – The number of times to execute the function. Defaults to 1.
Returns: The class itself.
Return type: classmethod repeat_ms(interval_ms: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, iterations: int = 1, daemon: bool = False) -> Type[Self]
Repeatedly triggers a function at a specified interval in milliseconds for a set number of iterations.
Parameters:
- interval_ms (float* or **int*) – The time interval between each execution, in milliseconds.
- function (Callable) – The function to execute at each interval.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- iterations (int*, **optional*) – The number of times to execute the function. Defaults to 1.
- daemon (bool*, **optional*) – Whether to run the timer thread as a daemon. Defaults to False.
Returns: The class itself.
Return type: restart(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta', None] = 'PreciseTimeDelta') -> list[`PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta] | `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta | Self
Restarts an already running timer, skipping the whole .stop() .get_readable() .delete() boilerplate.
Parameters: Returns: The elapsed time(s) or TimidTimer: The current instance of the timer.
Return type: list[PreciseTimeDelta | timedelta] | PreciseTimeDelta | timedelta
resume(*indices: int | None) -> Self
Resumes the timer at the specified indices.
Parameters: indices (int*, **optional*) – The index or indices where the timer should be resumed. Defaults to the first paused timer. Returns: The current instance of the timer. Return type: FlexTimer save_state() -> bytes
Saves the current state of all timers (excluding threads).
Returns: A serialized representation of the timer’s state. Return type: bytes static schedule_task_at(time_str, callback: ~collections.abc.Callable[[...], ~typing.Any] = <built-in function print>, args: tuple[~typing.Any, ...] = (), kwargs: dict[str, ~typing.Any] | None = None) -> None
Schedules a task to run at a specified time of day, either today or the next day if the time has passed.
Parameters:
- time_str (str) – The time of day to run the task, in “HH:MM” or “HH:MM:SS” format.
- callback (Callable*, **optional*) – The function to run when the scheduled time is reached. Defaults to print.
- args (tuple*, **optional*) – The arguments for the callback function. Defaults to a message with the scheduled time.
- kwargs (dict*, **optional*) – The keyword arguments for the callback function. Defaults to None.
show_laps(index: int | None = None, format_to: PreciseTimeFormat = PreciseTimeFormat.SECONDS) -> str
Displays the recorded times for each tick and tock.
Parameters: Returns: The tick tocks of the index in a readable string format.
Return type: str
classmethod single_shot(wait_time: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, daemon: bool = False) -> Type[Self]
Executes a single-shot timer that triggers the specified function after a set amount of time.
Parameters:
- wait_time (float* or **int*) – The time to wait before executing the function, in seconds.
- function (Callable) – The function to execute after the timer ends.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- daemon (bool*, **optional*) – Whether to run the timer thread as a daemon. Defaults to False.
Returns: The class itself.
Return type: classmethod single_shot_long(wait_time: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None) -> Type[Self]
Executes a long-running single-shot timer that triggers the specified function after a set amount of time.
Parameters:
- wait_time (float* or **int*) – The time to wait before executing the function, in seconds.
- function (Callable) – The function to execute after the timer ends.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
Returns: The class itself.
Return type: classmethod single_shot_ms(wait_time_ms: int | float, function: Callable[[...], Any], args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, daemon: bool = False) -> Type[Self]
Executes a single-shot timer that triggers the specified function after a set amount of time in milliseconds.
Parameters:
- wait_time_ms (float* or **int*) – The time to wait before executing the function, in milliseconds.
- function (Callable) – The function to execute after the timer ends.
- args (tuple*, **optional*) – Arguments to pass to the function. Defaults to an empty tuple.
- kwargs (dict*, **optional*) – Keyword arguments to pass to the function. Defaults to None.
- daemon (bool*, **optional*) – Whether to run the timer thread as a daemon. Defaults to False.
Returns: The class itself.
Return type: start(*indices: int | None, start_at: int | float = 0) -> Self
Starts the timer at the specified indices.
Parameters: Returns: The current instance of the timer.
Return type: stop(*indices: int | None) -> Self
Stops the timer at the specified indices.
Parameters: indices (int*, **optional*) – The index or indices where the timer should be stopped. Defaults to the first active timer. Returns: The current instance of the timer. Return type: FlexTimer stop_loop(index: int | None = None, amount: int | None = None) -> Self
Stops the specified timer(s) and removes them from the internal list.
Parameters: Returns: The current instance of the timer.
Return type: stop_loops(*indices: int | None, not_exists_okay: bool = False) -> Self
Stops the specified timer(s) and removes them from the internal list.
Parameters:
- indices (int*, **optional*) – The indices of the timers to stop. Defaults to None (stops the first timer).
- not_exists_okay (bool) – Raise IndexError if index does not exist and this is False.
Returns: The current instance of the timer.
Return type: static system_time() -> str
This method retrieves the current system time and returns it in “HH:MM:SS” format. :return: The current system time.tally(*indices: int | None, return_type: Literal['timedelta', 'PreciseTimeDelta'] = 'PreciseTimeDelta') -> `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta
Returns the total time recorded across all ticks and tocks.
Parameters: Returns: The total elapsed time across all ticks and tocks.
Return type: PreciseTimeDelta | timedelta
classmethod test_delay(amount: int | float = 0, return_type: Literal['timedelta', 'PreciseTimeDelta'] = 'PreciseTimeDelta') -> `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta
Tests a delay of a specified amount of time and returns the elapsed time.
Parameters: Returns: The elapsed time during the delay.
Return type: PreciseTimeDelta | timedelta
classmethod test_delay_ms(amount_ms: int | float = 0, return_type: Literal['timedelta', 'PreciseTimeDelta'] = 'PreciseTimeDelta') -> `PreciseTimeDelta <#aplustools.package.chronokit.PreciseTimeDelta>`_ | timedelta
Tests a delay of a specified amount of time in milliseconds and returns the elapsed time.
Parameters: Returns: The elapsed time during the delay.
Return type: PreciseTimeDelta | timedelta
classmethod time(time_format: PreciseTimeFormat = PreciseTimeFormat.SECONDS) -> CallableCallable[[...], Any, Callable...], Any
A decorator to measure the execution time of a function and print the result.
This decorator uses the TimidTimer class to time how long a specific function takes to execute. The result is printed in the specified time format, and the function’s return value is passed through.
Parameters: time_format (TimeFormat*, **optional*) – The time format to display the elapsed time. Defaults to TimeFormat.SECONDS. Returns: A decorator function. Return type: Callable wait(seconds: int | float = 0) -> Self
Pauses execution for a specified number of seconds.
Parameters: seconds (int*, **optional*) – The time to wait in seconds. Defaults to 0. Returns: The current instance of the timer. Return type: FlexTimer wait_ms(milliseconds: int | float = 0) -> Self
Pauses execution for a specified number of milliseconds.
Parameters: milliseconds (int*, **optional*) – The time to wait in milliseconds. Defaults to 0. Returns: The current instance of the timer. Return type: FlexTimer classmethod wait_ms_static(milliseconds: int | float = 0) -> Type[Self]
Pauses execution for a specified number of milliseconds, statically.
Parameters: milliseconds (int*, **optional*) – The time to wait in milliseconds. Defaults to 0. Returns: The class itself. Return type: FlexTimer classmethod wait_static(seconds: int | float = 0) -> Type[Self]
Pauses execution for a specified number of seconds, statically.
Parameters: seconds (int*, **optional*) – The time to wait in seconds. Defaults to 0. Returns: The class itself. Return type: FlexTimer warmup_timer(rounds: int = 300) -> Self
Warms up the timer by running short intervals repeatedly.
Parameters: rounds (int*, **optional*) – The number of warmup rounds. Defaults to 300. Returns: The current instance of the timer. Return type: FlexTimer
class aplustools.package.chronokit.MonotonicFTimer(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.MonotonicFTimerNS(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.PerfFTimer(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.PerfFTimerNS(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.PreciseTimeDelta(years: float = 0, months: float = 0, weeks: float = 0, days: float = 0, hours: float = 0, minutes: float = 0, seconds: float = 0, milliseconds: float = 0, microseconds: float = 0, nanoseconds: float = 0, picoseconds: float = 0, femtoseconds: float = 0, attoseconds: float = 0, max_precision: int = 10)
Bases:
objectA class to represent small and precise time differences, allowing arithmetic operations and formatted output. This class handles time values from years to attoseconds and stores the total time in nanoseconds internally.
negativeIndicates if the time difference is negative.
Type: bool
_total_nanosecondsThe total time difference in nanoseconds, including fractional precision.
Type: float
max_precisionNumber of decimal digits to display.
Type: int
DAYS_IN_MONTH = 30.44
DAYS_IN_WEEK = 7
DAYS_IN_YEAR = 365.25
NANOS_PER_DAY = 86400000000000.0
NANOS_PER_HOUR = 3600000000000.0
NANOS_PER_MICROSECOND = 1000.0
NANOS_PER_MILLISECOND = 1000000.0
NANOS_PER_MINUTE = 60000000000.0
NANOS_PER_MONTH = 2630016000000000.0
NANOS_PER_SECOND = 1000000000.0
NANOS_PER_WEEK = 604800000000000.0
NANOS_PER_YEAR = 3.15576e+16
SECONDS_IN_DAY = 86400
SECONDS_IN_HOUR = 3600
SECONDS_IN_MINUTE = 60__init__(years: float = 0, months: float = 0, weeks: float = 0, days: float = 0, hours: float = 0, minutes: float = 0, seconds: float = 0, milliseconds: float = 0, microseconds: float = 0, nanoseconds: float = 0, picoseconds: float = 0, femtoseconds: float = 0, attoseconds: float = 0, max_precision: int = 10) -> None
Initializes the PreciseTimeDelta by converting all time formats into nanoseconds and summing them up.
Parameters:
- years (float) – Number of years in the time difference.
- months (float) – Number of months in the time difference.
- weeks (float) – Number of weeks in the time difference.
- days (float) – Number of days in the time difference.
- hours (float) – Number of hours in the time difference.
- minutes (float) – Number of minutes in the time difference.
- seconds (float) – Number of seconds in the time difference.
- milliseconds (float) – Number of milliseconds in the time difference.
- microseconds (float) – Number of microseconds in the time difference.
- nanoseconds (float) – Number of nanoseconds in the time difference.
- picoseconds (float) – Number of picoseconds in the time difference.
- femtoseconds (float) – Number of femtoseconds in the time difference.
- attoseconds (float) – Number of attoseconds in the time difference.
- max_precision (int) – Number of decimal digits to display for fractional seconds.
attoseconds() -> float
Returns the number of attoseconds in the time difference.
Returns: The number of attoseconds. Return type: float days() -> float
Returns the number of days in the time difference.
Returns: The number of days. Return type: float femtoseconds() -> float
Returns the number of femtoseconds in the time difference.
Returns: The number of femtoseconds. Return type: float classmethod from_timedelta(td: timedelta) -> Self
Convert a timedelta object into nanoseconds. :param td: The timedelta object to convert. :return: The equivalent PreciseTimeDelta.hours() -> float
Returns the number of hours in the time difference.
Returns: The number of hours. Return type: float microseconds() -> float
Returns the number of microseconds in the time difference.
Returns: The number of microseconds. Return type: float milliseconds() -> float
Returns the number of milliseconds in the time difference.
Returns: The number of milliseconds. Return type: float minutes() -> float
Returns the number of minutes in the time difference.
Returns: The number of minutes. Return type: float months() -> float
Returns the number of months in the time difference.
Returns: The number of months. Return type: float nanoseconds() -> float
Returns the number of nanoseconds in the time difference.
Returns: The number of nanoseconds. Return type: float classmethod parse_timedelta_string(td_str: str) -> Self
Convert a timedelta-like string format (e.g., ‘00:00:00.123456789’) into nanoseconds.
Parameters: td_str (str) – A string in the form ‘HH:MM:SS.fffffffff’ Returns: Equivalent nanoseconds. Return type: int picoseconds() -> float
Returns the number of picoseconds in the time difference.
Returns: The number of picoseconds. Return type: float seconds() -> float
Returns the number of seconds in the time difference.
Returns: The number of seconds. Return type: float to_clock_string() -> str
Convert nanoseconds into a human-readable format with arbitrary precision, displaying the time in a format like 00:00:00.0000000000.
Returns: Human-readable string with days, weeks, months, and years if applicable. Return type: str to_readable(format_to: PreciseTimeFormat | None = None, max_precision: int | None = None) -> str
Convert a given timedelta to a human-readable string based on the specified time format. If no format is provided, it defaults to seconds. :param format_to: The time unit format to convert to. If None, defaults to SECONDS. :param max_precision: :return: A human-readable string representing the timedelta in the specified time format.to_timedelta() -> timedelta
Convert nanoseconds into a timedelta object. :return: Corresponding timedelta object.weeks() -> float
Returns the number of weeks in the time difference.
Returns: The number of weeks. Return type: float years() -> float
Returns the number of years in the time difference.
Returns: The number of years. Return type: float
class aplustools.package.chronokit.PreciseTimeFormat(*values)
Bases:
Enum
YEARSConstant representing the time unit ‘years’.
Type: int
MONTHSConstant representing the time unit ‘months’.
Type: int
WEEKSConstant representing the time unit ‘weeks’.
Type: int
DAYSConstant representing the time unit ‘days’.
Type: int
HOURSConstant representing the time unit ‘hours’.
Type: int
MINUTESConstant representing the time unit ‘minutes’.
Type: int
SECONDSConstant representing the time unit ‘seconds’.
Type: int
MILLISECSConstant representing the time unit ‘milliseconds’.
Type: int
MICROSECSConstant representing the time unit ‘microseconds’.
Type: int
NANOSECSConstant representing the time unit ‘nanoseconds’.
Type: int
PICOSECSConstant representing the time unit ‘picoseconds’.
Type: int
FEMTOSECSConstant representing the time unit ‘femtoseconds’.
Type: int
ATTOSECSConstant representing the time unit ‘attoseconds’.
Type: int
ATTOSECS = 2048
DAYS = 4
FEMTOSECS = 1024
HOURS = 8
MICROSECS = 128
MILLISECS = 64
MINUTES = 16
MONTHS = 1
NANOSECS = 256
PICOSECS = 512
SECONDS = 32
WEEKS = 2
YEARS = 0
class aplustools.package.chronokit.ThreadFTimer(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.ThreadFTimerNS(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.TimeFTimer(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
class aplustools.package.chronokit.TimeFTimerNS(start_at: int | float = 0, start_now: bool = True)
Bases: FlexTimer
Module providing lazy loading of specific submodules and dynamic imports for the aplus tools package.
This module leverages a LazyLoader to lazily load the timid and argumint modules when they are first accessed. It also dynamically imports public members from the _direct module, updates the __all__ list, and cleans up globals to remove private symbols (those starting with an underscore).
aplustools.package.timid
Lazy loader for the timid submodule.
Type: LazyLoader
aplustools.package.argumint
Lazy loader for the argumint submodule.
Type: LazyLoader
aplustools.package.__all__
List of public symbols exported by this module, including dynamically added symbols from the _direct module.
Type: list
Lazy loading allows for deferred loading of these modules, improving performance and memory efficiency in cases where they are not always needed.
class aplustools.package.LazyLoader(module_name: str)
Bases:
objectLazyModuleLoader is a utility for lazy-loading Python modules and their submodules, with dependency checks.
This class allows for deferred loading of modules until they are actually used, improving performance in cases where a module may not always be necessary. It also checks for required dependencies specified in the module’s __deps__ attribute, issuing warnings if any dependencies are missing or do not meet version specifications.
Features: - Lazy-loads modules and submodules. - Handles both absolute and relative imports. - Checks module dependencies and raises warnings for missing or incompatible dependencies. - Provides a load_all() method to eagerly load all submodules at once.
Parameters: module_name (str) – The name of the module or package to load. Can handle both packages (e.g., ‘aps.io’) and modules. load_all()
Loads the specified module and all its submodules eagerly.
- Usage Example:
- loader = LazyModuleLoader(‘aps.io’) # Access module properties lazily io = loader.some_property # Eagerly load all submodules loader.load_all()
__init__(module_name: str) -> None
aplustools.package.check_if_available(module_spec: str) -> bool
Checks if a module spec is available using importlib and packaging.specifiers. Returns True if module spec is available, otherwise False.
Parameters: module_spec – e.g. ‘PySide6>=6.7.0’ Returns: True if available, otherwise False.
aplustools.package.enforce_hard_deps(hard_deps: list[str], module_name: str) -> None
Enforces all hard dependencies passed as hard_deps. Raises a ModuleNotFound error for any missing.
Parameters:
- hard_deps – List of hard dep specs e.g. ‘PySide>=6.7.0’.
- module_name – __name__ of the current module.
Returns: None
aplustools.package.optional_import(module_name: str, fromlist: list | None = None) -> ModuleType | None
Attempt to import a module by its name. Return the module if available, otherwise return None.
Parameters:
- module_name (str) – The name of the module to import.
- fromlist (list) – List of internal classes to import.
Returns: The imported module if successful, or None if the import fails.
Return type: module
aplustools.package.setup_lazy_loaders(module_globals: dict[str, Any], lazy_modules: dict[str, str], direct_module: ModuleType | None = None)
Set up lazy loaders for specified submodules and dynamically import members from a direct module.
This function configures lazy loaders for submodules and dynamically imports public members from the specified direct module without overwriting existing global variables that would later be cleaned up.
Parameters:
- module_globals (dict) – The global dictionary of the calling module (typically globals()).
- lazy_modules (dict) – A dictionary of module names to be lazy-loaded, where the key is the attribute name and the value is the module path.
- direct_module (module*, **optional*) – The direct module from which to dynamically import public members. If not provided, no dynamic imports will occur.
- Example Usage:
- lazy_modules = {
- “timid”: “aplustools.package.timid”, “argumint”: “aplustools.package.argumint”
} setup_lazy_loaders(globals(), lazy_modules, some_direct_module)