Skip to content

zzlib.func module

zzlib.func

zzlib.func.async_call(obj, *args, **kw) async

Recognize the input as async function, general function, awaitable, or constants. Execute them according to their type. The remaining arguments are passed to the function.

zzlib.func.async_optional_lock(lock) async

Allows the async lock to be ignored if it is None.

zzlib.func.chain_decos(*decos)

A decorator that allows us to chain multiple decorators.

Example
@chain_decos(deco1, deco2, deco3)
def func():
    pass

zzlib.func.class_path(cls)

Get the full path of an object with the module name.

Returns:

Type Description
str

The full path as module.class.name or just class.name for builtins

zzlib.func.convert(call, *, force=False)

A decorator that converts function arguments to their type hints.

This decorator attempts to automatically convert function arguments to match their type hints. For example, if a function expects an int but receives a string, the decorator will try to convert the string to an int.

Parameters:

Name Type Description Default
force bool

If True, raise ConvertError when type conversion fails. If False, silently keep original value. Default is False.

False
Example
@convert
def add(x: int, y: int) -> int:
    return x + y

result = add("1", "2")  # Converts strings to ints
assert result == 3

@convert(force=True)
def strict_add(x: int, y: int) -> int:
    return x + y

strict_add("a", "b")  # Raises ConvertError

zzlib.func.count(iter)

Count total item number of an iterator.

zzlib.func.flatten(l)

Flatten a irregular n-dimensional list to a 1-dimensional list.

zzlib.func.flatten2(l)

Flatten a 2-dimensional list to a 1-dimensional list.

zzlib.func.format_bytes_human(B)

Return the given bytes as a human friendly KB, MB, GB, or TB string.

zzlib.func.format_timedelta(td)

Format timedelta to d:hh:mm:ss.

zzlib.func.format_timedelta_human(delta)

Format timedelta to human readable string like '2 days, 3 hours, 1 minute'.

zzlib.func.get_after_char(text, delim)

Get characters after the first occurence of delim.

Example
text = "hello:world"
result = get_after_char(text, ":")
assert result == "world"

zzlib.func.has_len(iter, min_len=1)

Check if an iterator has items more than min_len.

zzlib.func.in_range(t, v)

Check if a value falls within a specified range [a, b].

Parameters:

Name Type Description Default
t Tuple[Union[float, None]]

An iterable containing two elements that define the range [a, b]. Each element can be a float or None, where None represents negative infinity for a and positive infinity for b.

required
v float

The value to check against the range.

required

zzlib.func.is_in_notebook()

Check the script is run in jupyter notebook.

zzlib.func.is_iterable(var)

Check if iterable.

zzlib.func.median(lst)

Calculate the median of the list values.

zzlib.func.next_or_none(iter)

Return next of the generator, else None.

zzlib.func.nonblocking(lock)

Try to acquire the lock, if the lock is already acquired by other threads, skip the entire with block.

zzlib.func.optional_lock(lock) async

Allows the lock to be ignored if it is None.

zzlib.func.path_to_str(data, absolute=False)

Convert Path objects to strings recursively.

This function converts Path objects to strings. It can process Path objects directly, as well as Paths contained in lists and dictionaries.

Parameters:

Name Type Description Default
data Union[Path, List, Dict]

Input data that may contain Path objects.

required
absolute bool

If True, converts Paths to absolute paths. Default is False.

False
Example
data = {
    'path': Path('dir/file.txt'),
    'paths': [Path('a.txt'), Path('b.txt')]
}
result = path_to_str(data) # (1)
  1. Returns:
    {
        'path': 'dir/file.txt',
        'paths': ['a.txt', 'b.txt']
    }
    

zzlib.func.pipeline(*steps)

Create a function pipeline by composing multiple functions together.

The pipeline executes functions in sequence, where each function's output becomes the input to the next function in the pipeline.

Parameters:

Name Type Description Default
*steps Callable

Variable number of functions to compose into a pipeline.

()

Returns:

Type Description
Callable

A composed function that executes the pipeline when called.

Example
def add_one(x): return x + 1
def double(x): return x * 2

pipeline_func = pipeline(add_one, double)
result = pipeline_func(5)  # Returns 12: ((5 + 1) * 2)

zzlib.func.product_nested(l)

Product an irregular 2-dimensional list.

zzlib.func.raise_in_thread(thread, exception)

Raise an exception in a target thread to force termination.

Warning

Only works in CPython due to implementation details.

Parameters:

Name Type Description Default
thread Union[Thread, int]

Thread object or thread ID to raise exception in.

required
exception Exception

Exception instance to raise in the target thread.

required

zzlib.func.reflection(spec)

Import and return a class or function by its fully qualified name.

Parameters:

Name Type Description Default
spec str

A string specifying the object to import, in the format module.submodule.object or just object / str / int for builtins.

required
Example
# Import built-in str class
str_class = reflection('str')

# Import Path from pathlib
path_class = reflection('pathlib.Path')

zzlib.func.remove_outliers(lst)

Remove outliers from the list. Return the corrected list.

zzlib.func.remove_prefix(text, prefix)

Remove prefix from the begining of text.

zzlib.func.rename_dup_in(l)

Rename duplicated names in a list with increasing suffixes from 1.

zzlib.func.split_kw(kw, keys, drops=())

Split kw into filtered and others by specifying keys.

zzlib.func.suffix_dup(l)

Rename duplicated names in a list with increasing suffixes.

Example
names = ['a', 'b', 'a', 'c', 'b', 'a']
result = suffix_dup(names)
assert result == ['a_1', 'b_1', 'a_2', 'c', 'b_2', 'a_3']

zzlib.func.to_exception(var, default=RuntimeError)

Convert the value into a error when specifying error message, Exception or Exception instance.

zzlib.func.to_iterable(var)

Convert the value into a list if it is not an Iterable.

zzlib.func.truncate_path(f, length)

Truncate a path str to a certain length, and the omitted part is represented by "...".

zzlib.func.truncate_str(text, length)

Truncate a str to a certain length, and the omitted part is represented by "...".

zzlib.func.walk(l)

Iterate over a irregular n-dimensional list.