Skip to content

Utils

json

loads: typing.Callable[[typing.Union[str, bytes, bytearray, memoryview]], typing.Any] = orjson.loads module-attribute

Deserialize a JSON string to a Python object.

Parameters:

Name Type Description Default
s (bytes, str, bytearray, memoryview)

The JSON string to be deserialized.

required

Returns:

Type Description
typing.Callable[[typing.Union[str, bytes, bytearray, memoryview]], typing.Any]

typing.Any: The deserialized Python object.

dump(val, fp, *, default=None)

Serialize a Python object and write the JSON-formatted string to a text file object.

Parameters:

Name Type Description Default
val typing.Any

The Python object to be serialized.

required
fp typing.TextIO

The text file object to write the JSON-formatted string to.

required
default typing.Any

A default value to be used if an object is not serializable. Defaults to None.

None

dumps(val, *, default=None)

Serialize a Python object to a JSON-formatted string.

Parameters:

Name Type Description Default
val typing.Any

The Python object to be serialized.

required
default typing.Any

A default value to be used if an object is not serializable. Defaults to None.

None

Returns:

Name Type Description
str str

The JSON-formatted string representing the serialized object.

load(fdes)

Deserialize a JSON-formatted string from a text file object.

Parameters:

Name Type Description Default
fdes typing.TextIO

The text file object to read the JSON-formatted string from.

required

Returns:

Type Description
str

typing.Any: The deserialized Python object.

timezone

make_now_factory(tz)

Create a function to get the current aware datetime with a specific timezone.

Parameters:

Name Type Description Default
tz tzinfo

The timezone for the datetime factory.

required

Returns:

Type Description
Callable[[], datetime]

Callable[[], datetime]: A function that returns the current datetime in the specified timezone.

now(tz=timezone.utc)

Get the current aware datetime.

Parameters:

Name Type Description Default
tz tzinfo

The timezone for the datetime (default is UTC).

timezone.utc

Returns:

Name Type Description
datetime datetime

The current datetime in the specified timezone.

today(tz=timezone.utc)

Get today's aware date.

Parameters:

Name Type Description Default
tz tzinfo

The timezone for the date (default is UTC).

timezone.utc

Returns:

Name Type Description
date date

Today's date in the specified timezone.

strings

make_lex_separator(outer_cast, cast=str)

Create a lexer-based separator function.

Parameters:

Name Type Description Default
outer_cast type

The type to cast the resulting separated values into.

required
cast type

The type to which each individual item will be cast (default: str).

str

Returns:

Type Description
Callable[[str], OuterCastT]

Callable[[str], OuterCastT]: A callable that separates a string into an instance of outer_cast with casted items.

Examples:

>>> comma_separated = make_lex_separator(tuple, str)
>>> result = comma_separated("a, b, c")
>>> print(result)
('a', 'b', 'c')

to_camel(snake_string)

Convert a snake_case string to camelCase.

Parameters:

Name Type Description Default
snake_string str

The snake_case string to be converted.

required

Returns:

Name Type Description
str str

The converted string in camelCase.

to_lower_kebab(camel_string)

Convert camelCase strings to kebab-case.

Parameters:

Name Type Description Default
camel_string str

The camelCase string to be converted.

required

Returns:

Name Type Description
str str

The converted string in kebab-case.

to_pascal(snake_string)

Convert a snake_case string to PascalCase.

Parameters:

Name Type Description Default
snake_string str

The snake_case string to be converted.

required

Returns:

Name Type Description
str str

The converted string in PascalCase.

to_snake(camel_string)

Convert a camelCase string to snake_case.

Parameters:

Name Type Description Default
camel_string str

The camelCase string to be converted.

required

Returns:

Name Type Description
str str

The converted string in snake_case.

upper_camel(snake_string)

Deprecated

Use to_pascal instead.

finder

FinderBuilder

Builder class to construct a Finder instance with various configurations.

add_validator(validator)

Add a validation function to the builder.

Parameters:

Name Type Description Default
validator Validator

The validation function to add.

required

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

build(look_on=None)

Build a Finder instance with the provided configurations.

Parameters:

Name Type Description Default
look_on Optional[pathlib.Path]

The path to focus the search on (default: None).

None

Returns:

Name Type Description
_Finder _Finder

The built Finder instance.

child_of(*types)

Add a class validator that checks if objects are subclasses of the provided types.

Parameters:

Name Type Description Default
*types type

Types to validate against.

()

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

exclude(*paths)

Exclude paths from search.

Parameters:

Name Type Description Default
*paths StrOrPath

Paths to exclude.

()

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

exclude_default()

Exclude default paths (e.g., 'init.py', 'pycache') from search.

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

find(look_on=None)

Find and return located objects using the provided configurations.

Parameters:

Name Type Description Default
look_on Optional[pathlib.Path]

The path to focus the search on (default: None).

None

Returns:

Name Type Description
dict dict[str, typing.Any]

The dictionary containing the located objects.

from_cwd()

Set the root path for the finder to the current working directory.

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

from_package(stack_position=1)

Set the root path for the finder to the calling package root.

Parameters:

Name Type Description Default
stack_position int

The position in the stack trace of the calling function (default: 1).

1

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

from_path(path)

Set the root path for the finder from a provided path.

Parameters:

Name Type Description Default
path pathlib.Path

The root path.

required

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

Raises:

Type Description
InvalidPath

If the path does not exist

from_project()

Set the root path for the finder to the project root.

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

instance_of(*types)

Add an instance validator that checks if objects are instances of the provided types.

Parameters:

Name Type Description Default
*types type

Types to validate against.

()

Returns:

Name Type Description
FinderBuilder Self

The FinderBuilder instance.

reset()

Reset the builder to its initial state.

class_validator(*types)

Create a class validator that checks if objects are subclasses of the provided types.

Parameters:

Name Type Description Default
*types type

Types to validate against.

()

Returns:

Name Type Description
Validator Validator

The validator function.

instance_validator(*types)

Create an instance validator that checks if objects are instances of the provided types.

Parameters:

Name Type Description Default
*types type

Types to validate against.

()

Returns:

Name Type Description
Validator Validator

The validator function.

iterate_module(modpath, resolver)

Iterate through a module using a resolver to map paths to module names.

Parameters:

Name Type Description Default
modpath pathlib.Path

The path to the module.

required
resolver PathConverter

A path converter to map paths to module names.

required

Yields:

Type Description
str

tuple[str, Any]: A tuple containing the name and object of each item in the module.

make_modulename_resolver(root, path_converter=pathlib.Path.as_posix)

Create a module name resolver based on a root path.

Parameters:

Name Type Description Default
root pathlib.Path

The root path to resolve from.

required
path_converter PathConverter

A path converter function (default: pathlib.Path.as_posix).

pathlib.Path.as_posix

Returns:

Name Type Description
PathConverter PathConverter

A callable that resolves a path into a module name.

helpers

DeprecatedClass

A class to mark as deprecated.

This class issues a deprecation warning when instantiated.

cache(f)

Cache the result of a function. It uses functools.cache and just adds proper type hints to it.

Parameters:

Name Type Description Default
f Callable[P, T]

The function to be cached.

required

Returns:

Type Description
Callable[P, T]

Callable[P, T]: The cached version of the function.

deprecated(func)

Mark a function as deprecated and issue a warning when it's used.

Parameters:

Name Type Description Default
func Callable[P, T]

The function to be marked as deprecated.

required

Returns:

Type Description
Callable[P, T]

Callable[P, T]: A wrapped version of the function that issues a warning on use.

merge_dicts(left, right, on_conflict, merge_sequences=True)

Merge two dictionaries with customizable conflict resolution strategy.

Parameters:

Name Type Description Default
left dict

The left dictionary to merge.

required
right dict

The right dictionary to merge.

required
on_conflict Literal['strict', 'left', 'right']

The conflict resolution strategy to use.

  • 'strict': Raise a MergeConflict exception if conflicts occur.
  • 'left': Prioritize the values from the left dictionary in case of conflicts.
  • 'right': Prioritize the values from the right dictionary in case of conflicts.
required
merge_sequences bool

Indicates whether to merge sequences (lists, sets, tuples) or skip them.

  • If True, sequences will be merged based on the conflict resolution strategy.
  • If False, sequences will be skipped, and the value from the chosen (defaults to left on strict) dictionary will be used. Default is True.
True

Returns:

Name Type Description
dict dict

The merged dictionary.

Raises:

Type Description
MergeConflict

If conflicts occur and the conflict resolution strategy is set to 'strict'.

exc

panic(exc, message, *args)

Create an instance of the specified exception class with a modified error message.

This function creates an exception instance by calling the constructor of the specified exception class with the modified error message and any additional arguments provided.

Parameters:

Name Type Description Default
exc type[T]

The exception class to instantiate.

required
message str

The error message for the exception.

required
*args Any

Additional arguments to pass to the exception constructor.

()

Returns:

Name Type Description
T T

An instance of the specified exception class.

Examples:

>>> class CustomError(Exception):
...     pass
...
>>> error = panic(CustomError, "Something went wrong", "additional_info")
>>> isinstance(error, CustomError)
True
>>> str(error)
'Something went wrong! additional_info'

InvalidField

Bases: KeyError

Raised when an unexpected result is encountered during a field lookup on a mapping.

asynclazyfield

Bases: lazy, typing.Generic[SelfT, T]

A descriptor class for asynchronously lazy-loading attributes on a class.

When the decorated method is accessed on an instance, it will check if the instance has an attribute with the same name as the method but with an underscore prefix. If the attribute does not exist, it will call the decorated asynchronous method on the instance and set the result as the attribute's value. Subsequent accesses will return the cached value, avoiding unnecessary recalculation or computation.

__call__(instance) async

Call the asynchronous method to load the attribute's value.

Parameters:

Name Type Description Default
instance SelfT

The instance of the class.

required

Returns:

Name Type Description
T T

The loaded value of the attribute.

__get__(instance, owner=None)

Get the wrapped asynchronous method or the descriptor itself.

Parameters:

Name Type Description Default
instance typing.Optional[SelfT]

The instance of the class.

required
owner type[SelfT]

The class that owns the descriptor.

None

Returns:

Type Description
typing.Union[typing.Callable[[], typing.Coroutine[Any, Any, T]], Self]

Union[ typing.Callable[[], typing.Coroutine[Any, Any, T]], Self

typing.Union[typing.Callable[[], typing.Coroutine[Any, Any, T]], Self]

]: The asynchronous method or the descriptor itself.

__init__(func)

Initializes the asynclazyfield descriptor.

Parameters:

Name Type Description Default
func callable

The asynchronous function that will be decorated.

required

__set_name__(owner, name)

Set the public and private names for the asynclazyfield descriptor.

Parameters:

Name Type Description Default
owner type

The class that owns the descriptor.

required
name str

The name of the attribute.

required

lazy

Represents a lazy descriptor

lazyfield

Bases: lazy, typing.Generic[SelfT, T]

A descriptor class that can be used as a decorator for a method on a class. When the decorated method is accessed on an instance, it will check if the instance has an attribute with the same name as the method but with an underscore prefix. If the attribute does not exist, it will call the decorated method on the instance and set the result as the attribute's value. Subsequent accesses will return the cached value, avoiding unnecessary recalculation or computation.

__init__(func)

Initializes the lazy field descriptor.

Parameters:

Name Type Description Default
func callable

The function that will be decorated.

required

__set_name__(owner, name)

Sets the public and private names for the lazy field descriptor.

Parameters:

Name Type Description Default
owner type

The class that owns the descriptor.

required
name str

The name of the attribute.

required

dellazy(instance, attribute, bypass_delattr=False)

Delete the value of a lazy-loaded property on an instance.

Parameters:

Name Type Description Default
instance Any

The instance to delete the property from.

required
attribute str

The name of the lazy-loaded property.

required
bypass_delattr bool

If True, directly delete the attribute using object.__delattr__ to bypass immutability issues. (default: False)

False

Raises:

Type Description
InvalidField

If the attribute is not a lazy descriptor.

force_del(instance, attribute)

Forcefully delete the value of a lazy-loaded property on an instance.

Parameters:

Name Type Description Default
instance Any

The instance to set the property on.

required
attribute str

The name of the lazy-loaded property.

required

force_set(instance, attribute, value)

Forcefully set the value of a lazy-loaded property on an instance.

Parameters:

Name Type Description Default
instance Any

The instance to set the property on.

required
attribute str

The name of the lazy-loaded property.

required
value Any

The value to set for the property.

required

setlazy(instance, attribute, value, bypass_setattr=False)

Set the value of a lazy-loaded property on an instance.

Parameters:

Name Type Description Default
instance Any

The instance to set the property on.

required
attribute str

The name of the lazy-loaded property.

required
value Any

The value to set for the property.

required
bypass_setattr bool

If True, directly set the attribute using object.__setattr__ to bypass immutability issues. (default: False)

False

Raises:

Type Description
InvalidField

If the attribute is not a lazy descriptor.