Utility Functions#
Overview#
File Name: utils.py
This file provides various utility functions and classes for tasks such as file operations, generating random strings, and measuring execution time. It also includes a class for optimized progress updates.
Functions#
- get_current_user_name() str #
Returns the name of the currently logged-in user.
- Returns:
The current user’s name.
- Return type:
str
- make_int128(hi: int, lo: int) int #
Makes a 128-bit integer from two 64-bit integers.
- Parameters:
hi (int) – High 64 bits.
lo (int) – Low 64 bits.
- Returns:
128-bit integer combining hi and lo.
- Return type:
int
- html_escape(t: str) str #
Escapes special HTML characters in the provided text.
- Parameters:
t (str) – Text to escape.
- Returns:
Escaped text.
- Return type:
str
- get_available_system_memory() int #
Returns available system memory in bytes.
- Returns:
Available system memory in bytes.
- Return type:
int
- file_exists(path_name: str) bool #
Checks if a file specified by path_name exists.
- Parameters:
path_name (str) – Path to the file to check.
- Returns:
True if the file exists, False otherwise.
- Return type:
bool
- get_random_word(length: int) str #
Generates a random ASCII lowercase word of specified length using lowercase letters and digits.
- Parameters:
length (int) – Length of the random word.
- Returns:
Randomly generated word.
- Return type:
str
- get_temp_file_path_name(suffix: str = '') str #
Generates a temporary file path name with optional suffix.
- Parameters:
suffix (str, optional) – Optional suffix for the file name.
- Returns:
Temporary file path name.
- Return type:
str
- get_unique_temp_file_path_name(suffix: str = '') str #
Generates a unique temporary file path name that does not exist yet.
- Parameters:
suffix (str, optional) – Optional suffix for the file name.
- Returns:
Unique temporary file path name.
- Return type:
str
- is_local_url(url: str) bool #
Returns True if the URL points to a local file, False for remote URLs.
- Parameters:
url (str) – URL to check.
- Returns:
True if the URL is local, False otherwise.
- Return type:
bool
- safe_copy_file(
- src: str,
- dst: str,
- follow_symlinks: bool = True,
Safely copies src to dst. Supports URLs.
- Parameters:
src (str) – Source file path.
dst (str) – Destination file path.
follow_symlinks (bool, optional) – Whether to follow symlinks. Default is True.
- Returns:
True if the file is successfully copied, False otherwise.
- Return type:
bool
- safe_delete_file(file_name: str) bool #
Safely deletes a file from drive.
- Parameters:
file_name (str) – Name of the file to delete.
- Returns:
True if the file is successfully deleted, False otherwise.
- Return type:
bool
- clamp_value(value: Any, min_value: Any, max_value: Any) Any #
Clamps value within the min and max range.
- Parameters:
value – Value to clamp.
min_value – Minimum allowable value.
max_value – Maximum allowable value.
- Returns:
The clamped value.
- to_json_str_safe(obj: Any, **kwargs) str #
Safely converts a Python object into a JSON string.
This function attempts to serialize a Python object into a JSON-formatted string. If serialization fails, it logs an error message and returns an empty string. By default, the JSON string is formatted with an indentation of 4 spaces, unless otherwise specified in the keyword arguments.
- Parameters:
obj (Any) – The Python object to be serialized into a JSON string.
kwargs – Additional keyword arguments for json.dumps().
- Returns:
JSON string representation or empty string on failure.
- Return type:
str
- from_json_str_safe(json_str: str) Any #
Safely converts a JSON string into a Python object.
This function attempts to parse a JSON-encoded string into a corresponding Python object. If the input string is empty or an error occurs during parsing, it logs an error message and returns an empty list.
- Parameters:
json_str (str) – The JSON string to be converted.
- Returns:
Parsed Python object or empty list on failure.
- Return type:
Any
- obj_to_dict(
- obj: Any,
- attr_convert_fn: Callable[[str, Any], Any] | None = None,
Converts an object instance to a dictionary, handling Enum and datetime types.
- Parameters:
obj – Object to convert.
attr_convert_fn – Optional function to convert attribute values.
- Returns:
Dictionary of object attributes.
- Return type:
Dict[str, Any]
- dict_to_obj(
- obj: Any,
- data: Dict[str, Any],
- attr_convert_fn: Callable[[str, Any], Any] | None = None,
Converts a dictionary to an object instance.
- Parameters:
obj – Target object to populate.
data – Source dictionary.
attr_convert_fn – Optional function to convert values.
- Returns:
True on success.
- Return type:
bool
- measure_execution_time(func: Callable) Callable #
Decorator that measures and prints function execution time.
- Parameters:
func (Callable) – The function to measure.
- Returns:
Wrapped function with execution time measurement.
- Return type:
Callable
Classes#
OptimizedProgressUpdate class#
A utility class to manage progress updates efficiently by limiting excessive updates.
This class determines whether a progress update should be propagated based on the elapsed time since the last update and the change in progress value. It ensures that updates are sent at a controlled rate, preventing unnecessary updates.
Constructor:#
- __init__(
- update_rate: float = 0.1,
- force_update_rate: float = 1.0,
- auto_start: bool = True,
Initializes the OptimizedProgressUpdate instance.
- Parameters:
update_rate (float, optional) – The rate at which updates are allowed, in seconds. Default is 0.1.
force_update_rate – Maximum interval before forcing an update, in seconds. Default is 1.0.
auto_start (bool, optional) – Whether to start the progress update automatically. Default is True.
Attributes:#
- progress_value: float#
Holds progress value [0.0..1.0+].
Methods:#
- start() None #
Resets the progress tracking state.
This method initializes or resets the internal state, ensuring that the first update is allowed immediately after calling this method.
- update(progress_value) bool #
Determines whether a progress update should be propagated.
An update is triggered if either: - The elapsed time since the last update exceeds force_update_rate, or - The progress value has changed and the elapsed time exceeds update_rate.
- Parameters:
progress_value (float) – Current progress value in range [0.0..1.0+].
- Returns:
True if the update should be propagated, otherwise False.
- Return type:
bool