pythonwrench package

Python library with tools for typing, manipulating collections, and more!

class pythonwrench.Compose[source]
class pythonwrench.Compose(fn0: Iterable[Callable[[T], T]], /)
class pythonwrench.Compose(fn0: Callable[[T], U], /)
class pythonwrench.Compose(fn0: Callable[[T], Any], fn1: Callable[[Any], U], /)
class pythonwrench.Compose(fn0: Callable[[T], Any], fn1: Callable[[Any], Any], fn2: Callable[[Any], U], /)
class pythonwrench.Compose(fn0: Callable[[T], Any], fn1: Callable[[Any], Any], fn2: Callable[[Any], Any], fn3: Callable[[Any], U], /)
class pythonwrench.Compose(fn0: Callable[[T], Any], fn1: Callable[[Any], Any], fn2: Callable[[Any], Any], fn3: Callable[[Any], Any], fn4: Callable[[Any], U], /)
class pythonwrench.Compose(*fns: Callable)

Bases: Generic[T, U]

Compose callables to chain calls sequentially.

class pythonwrench.DataclassInstance(*args, **kwargs)[source]

Bases: Protocol

pythonwrench.EllipsisType

alias of EllipsisType

class pythonwrench.MkdirFileHandler(filename: str | Path, mode: str = 'a', encoding: str | None = None, delay: bool = True, errors: str | None = None, *, mkdir_parents: bool = True, mkdir_exist_ok: bool = True)[source]

Bases: FileHandler

FileHandler that build intermediate directories to filename.

Used for export hydra logs to a file contained in a folder that does not exists yet at the start of the program.

class pythonwrench.NamedTupleInstance(*args, **kwargs)[source]

Bases: Protocol

class pythonwrench.NoneType

Bases: object

The type of the None singleton.

class pythonwrench.Singleton[source]

Bases: type

Singleton metaclass.

To use it, just inherit from metaclass.

Example

>>> class MyClass(metaclass=Singleton):
>>>     pass
>>> a1 = MyClass()
>>> a2 = MyClass()
>>> # a1 and a2 are exactly the same instance, i.e. id(a1) == id(a2)
class pythonwrench.StrEnum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: str, Enum

StrEnum is the same as Enum, but its members are also strings and can be used in most of the same places that a string can be used.

Note: when used as keys of dicts, enums are considered different from strings keys.

This class has the same objective than https://docs.python.org/3/library/enum.html#enum.StrEnum, which was introduced in Python 3.11.

classmethod from_str(value: str, case_sensitive: bool = False) Self[source]
property value : str
class pythonwrench.SupportsAdd(*args, **kwargs)[source]

Bases: Protocol[_T_Other]

Protocol that support __add__ (+) method.

class pythonwrench.SupportsAnd(*args, **kwargs)[source]

Bases: Protocol[_T_Other]

Protocol that support __and__ (&) method.

class pythonwrench.SupportsBool(*args, **kwargs)[source]

Bases: Protocol

Protocol that support __bool__ method.

class pythonwrench.SupportsDiv(*args, **kwargs)[source]

Bases: Protocol[_T_Other]

Protocol that support __div__ (/) method.

class pythonwrench.SupportsGetitem(*args, **kwargs)[source]

Bases: Protocol[_T_Item, _T_Index]

Protocol that support __getitem__ method.

class pythonwrench.SupportsGetitem2(*args, **kwargs)[source]

Bases: Protocol[_T_Index2, _T_Item]

Protocol that support __getitem__ method.

Same than SupportsGetitem except that generic parameters are in reversed order: [T_Index, T_Item].

class pythonwrench.SupportsGetitemIterLen(*args, **kwargs)[source]

Bases: Protocol[_T_Item, _T_Index]

Protocol that support __getitem__, __iter__ and __len__ methods.

class pythonwrench.SupportsGetitemIterLen2(*args, **kwargs)[source]

Bases: Protocol[_T_Index2, _T_Item]

Protocol that support __getitem__, __iter__ and __len__ methods.

Same than SupportsGetitemIterLen except that generic parameters are in reversed order: [T_Index, T_Item].

class pythonwrench.SupportsGetitemLen(*args, **kwargs)[source]

Bases: Protocol[_T_Item, _T_Index]

Protocol that support __getitem__ and __len__ methods.

class pythonwrench.SupportsGetitemLen2(*args, **kwargs)[source]

Bases: Protocol[_T_Index2, _T_Item]

Protocol that support __getitem__ and __len__ methods.

Same than SupportsGetitemLen except that generic parameters are in reversed order: [T_Index, T_Item].

class pythonwrench.SupportsIterLen(*args, **kwargs)[source]

Bases: Protocol[_T_Item]

Protocol that support __iter__ and __len__ methods.

class pythonwrench.SupportsLen(*args, **kwargs)[source]

Bases: Protocol

Protocol that support __len__ method.

class pythonwrench.SupportsMatmul(*args, **kwargs)[source]

Bases: Protocol[_T_Other]

Protocol that support __matmul__ (@) method.

class pythonwrench.SupportsMul(*args, **kwargs)[source]

Bases: Protocol[_T_Other]

Protocol that support __mul__ (*) method.

class pythonwrench.SupportsOr(*args, **kwargs)[source]

Bases: Protocol[_T_Other]

Protocol that support __or__ (|) method.

class pythonwrench.Version(version: Self, /)[source]
class pythonwrench.Version(version_str: str, /)
class pythonwrench.Version(version_dict: Mapping[str, int | str | None | list[str | int]], /)
class pythonwrench.Version(version_tuple: tuple[int | str | None | list[str | int], ...], /)
class pythonwrench.Version(major: int, minor: int, patch: int, prerelease: int | str | None | list[str | int] = None, buildmetadata: int | str | None | list[str | int] = None)

Bases: object

Version utility class following Semantic Versioning (SemVer) spec.

Version format is: MAJOR.MINOR.PATCH[-PRERELEASE][+BUILDMETADATA]

Based on https://semver.org/ version 2.0.0.

buildmetadata : int | str | None | List[str | int]
equals(other: Version | str | Mapping[str, int | str | None | list[str | int]] | tuple[int | str | None | list[str | int], ...], *, ignore_buildmetadata: bool = False) bool[source]
classmethod from_dict(version_dict: Mapping[str, int | str | None | list[str | int]]) Self[source]
classmethod from_str(version_str: str) Self[source]
classmethod from_tuple(version_tuple: tuple[int | str | None | list[str | int], ...]) Self[source]
major : int
property micro : int

Getter alias of ‘patch’.

minor : int
next_major(keep_prerelease: bool = False, keep_buildmetadata: bool = False) Version[source]
next_minor(keep_prerelease: bool = False, keep_buildmetadata: bool = False) Version[source]
next_patch(keep_prerelease: bool = False, keep_buildmetadata: bool = False) Version[source]
patch : int
prerelease : int | str | None | List[str | int]
classmethod python(releaselevel_in_metadata: bool = False) Self[source]

Create an instance of Version with Python version.

Note: Python ‘micro’ value is mapped to ‘patch’.

to_dict(exclude_none: bool = True) VersionDict[source]
to_str() str[source]
to_tuple(exclude_none: bool = True) tuple[int, int, int] | tuple[int, int, int, int | str | None | list[str | int]] | tuple[int, int, int, int | str | None | list[str | int], int | str | None | list[str | int]][source]
without_buildmetadata() Version[source]
without_prerelease() Version[source]
pythonwrench.all_eq(it: Iterable[T], eq_fn: Callable[[T, T], bool] | None = None) bool[source]

Returns true if all elements in iterable are equal.

Note: This function returns True for iterable that contains 0 or 1 element.

pythonwrench.all_ne(it: Iterable[T], ne_fn: Callable[[T, T], bool] | None = None, use_set: bool = False) bool[source]

Returns true if all elements in iterable are differents.

Note: This function returns True for iterable that contains 0 or 1 element.

pythonwrench.argmax(x: Iterable) int[source]
pythonwrench.argmin(x: Iterable) int[source]
pythonwrench.argsort(x: Iterable[T], *, key: Callable[[T], Any] | None = None, reverse: bool = False) list[int][source]
pythonwrench.as_builtin(x: Any, **kwargs) Any[source]

Convert an object to a sanitized python builtin equivalent recursively.

This function can be used to sanitize data before saving to a JSON, YAML or CSV file.

Additional objects to convert can be added dynamically with pythonwrench.register_as_builtin_fn function decorator.

Here is the list of default objects converted to built-in: - tuple -> list - collections.Counter -> dict - datetime.date -> str - argparse.Namespace -> dict - re.Pattern -> str - pathlib.Path -> str - enum.Enum -> str - Mapping -> dict - Iterable -> list - Dataclass -> dict - NamedTuple -> dict

Note: By default, tuple objects are converted to list.

Args:

x: Object to convert to built-in equivalent.

pythonwrench.check_args_types(fn: Callable[[P], T]) Callable[[P], T][source]

Decorator to check argument types before call to a function.

Example

>>> import pythonwrench as pw
>>> @pw.check_args_types
>>> def f(a: int, b: str) -> str:
>>>     return a * b
>>> f(1, "a")  # pass check
>>> f(1, 2)  # raises TypeError from decorator
pythonwrench.checksum_any(x: ~typing.Any, *, isinstance_fn: ~typing.Callable[[~typing.Any, type | tuple], bool] = <built-in function isinstance>, **kwargs) int[source]

Compute checksum integer value from an arbitrary object.

Supports most builtin types. Checksum can be used to compare objects. Not meant for security/cryptography.

pythonwrench.checksum_object(x: ~typing.Any, *, isinstance_fn: ~typing.Callable[[~typing.Any, type | tuple], bool] = <built-in function isinstance>, **kwargs) int[source]

Compute checksum integer value from an arbitrary object.

Supports most builtin types. Checksum can be used to compare objects. Not meant for security/cryptography.

pythonwrench.clamp(x: T_Real, xmin: T_Real | None = None, xmax: T_Real | None = None) T_Real[source]
pythonwrench.clip(x: T_Real, xmin: T_Real | None = None, xmax: T_Real | None = None) T_Real[source]
pythonwrench.compile_patterns(patterns: str | Pattern | Iterable[str | Pattern]) list[Pattern][source]

Compile patterns-like to a list.

pythonwrench.compose

alias of Compose

pythonwrench.contained(x: __SPHINX_IMMATERIAL_TYPE_VAR__V_T, include: ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_T] | None = None, exclude: ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_T] | None = None, *, match_fn: ~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__V_T, __SPHINX_IMMATERIAL_TYPE_VAR__V_T], bool] = <built-in function eq>, order: ~typing.Literal['left', 'right'] = 'right') bool[source]

Returns True if name in include set and not in exclude set.

pythonwrench.deprecated_alias(alternative: ~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__P_P], __SPHINX_IMMATERIAL_TYPE_VAR__V_U], msg_fmt: str = "Deprecated call to '{fn_name}', use '{alternative_name}' instead.", warn_fn: ~typing.Callable[[str], ~typing.Any] = functools.partial(<functools._lru_cache_wrapper object>, category=<class 'DeprecationWarning'>)) Callable[[...], Callable[[P], U]][source]

Decorator to wrap deprecated function aliases.

pythonwrench.deprecated_function(fn: ~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__P_P], __SPHINX_IMMATERIAL_TYPE_VAR__V_U] | None = None, /, *, msg_fmt: str = "Deprecated call to '{fn_name}'.", warn_fn: ~typing.Callable[[str], ~typing.Any] = functools.partial(<functools._lru_cache_wrapper object>, category=<class 'DeprecationWarning'>)) Callable[source]

Decorator to wrap deprecated functions.

pythonwrench.dict_list_to_list_dict(dic: Mapping[T, Iterable[U]], key_mode: 'intersect' | 'same' | 'union' = 'union', default_val: W = None) list[dict[T, U | W]][source]

Convert dict of lists with same sizes to list of dicts.

Example 1

>>> dic = {"a": [1, 2], "b": [3, 4]}
>>> dict_list_to_list_dict(dic)
... [{"a": 1, "b": 3}, {"a": 2, "b": 4}]

Example 2

>>> dic = {"a": [1, 2, 3], "b": [4], "c": [5, 6]}
>>> dict_list_to_list_dict(dic, key_mode="union", default=-1)
... [{"a": 1, "b": 4, "c": 5}, {"a": 2, "b": -1, "c": 6}, {"a": 3, "b": -1, "c": -1}]
pythonwrench.disk_cache_call(fn: ~typing.Callable[[...], __SPHINX_IMMATERIAL_TYPE_VAR__V_T], *args, cache_dpath: str | ~pathlib.Path | None = None, cache_force: bool = False, cache_verbose: int = 0, cache_checksum_fn: ~typing.Callable[[~typing.Tuple[~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__P_P], __SPHINX_IMMATERIAL_TYPE_VAR__V_T], ~typing.Tuple, ~typing.Dict[str, ~typing.Any]]], int] = <function checksum_any>, cache_saving_backend: ~typing.Literal['csv', 'json', 'pickle', 'custom', 'auto'] = 'auto', cache_fname_fmt: str | ~typing.Callable[[...], str] = '{fn_name}_{checksum_hex}{suffix}', cache_fname_fmt_args: ~typing.Iterable[str] | None = None, cache_dump_fn: ~typing.Callable[[~typing.Any, ~pathlib.Path], ~typing.Any] | None = None, cache_load_fn: ~typing.Callable[[~pathlib.Path], ~typing.Any] | None = None, cache_enable: bool = True, cache_store_mode: ~typing.Literal['outputs_only', 'outputs_metadata', 'outputs_metadata_inputs'] = 'outputs_only', **kwargs) T[source]

Call function and store output in a cache file.

Cache file is identified by the checksum of the function arguments, and stored by default in ‘~/.cache/disk_cache/<Function_name>/’ directory.

Example

>>> import pythonwrench as pw
>>> def heavy_processing():
>>>     # Lot of stuff here
>>>     ...
>>> outputs = pw.disk_cache_call(heavy_processing)  # first time function is called
>>> outputs = pw.disk_cache_call(heavy_processing)  # second time outputs is loaded from disk
Args:

fn: Function to store its output. By default, it must be a callable that returns a pickable object. cache_dpath: Cache directory path. defaults to ‘~/.cache/disk_cache’. cache_force: Force function call and overwrite cache. defaults to False. cache_verbose: Set verbose logging level. Higher means more verbose. defaults to 0. cache_checksum_fn: Checksum function to identify input arguments. defaults to pythonwrench.checksum_any. cache_saving_backend: Optional saving backend. Can be one of (‘csv’, ‘json’, ‘pickle’, ‘custom’, ‘auto’). defaults to ‘auto’. cache_fname_fmt: Cache filename format. defaults to ‘{fn_name}_{checksum_hex}{suffix}’. cache_dump_fn: Dump/save function to store outputs and overwrite saving backend. defaults to None. cache_load_fn: Load function to store outputs and overwrite saving backend. defaults to None. cache_enable: Enable disk cache. If False, the function has no effect. defaults to True. cache_store_mode: Disk cache storage mode. By default, it store function output and saved date into the cache file. defaults to ‘outputs_metadata’. *args: Positional arguments passed to the function. **kwargs: Keywords arguments passed to the function.

pythonwrench.disk_cache_decorator(fn: ~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__P_P], __SPHINX_IMMATERIAL_TYPE_VAR__V_T] | None = None, *, cache_dpath: str | ~pathlib.Path | None = None, cache_force: bool = False, cache_verbose: int = 0, cache_checksum_fn: ~typing.Callable[[~typing.Tuple[~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__P_P], __SPHINX_IMMATERIAL_TYPE_VAR__V_T], ~typing.Tuple, ~typing.Dict[str, ~typing.Any]]], int] = <function checksum_any>, cache_saving_backend: ~typing.Literal['csv', 'json', 'pickle', 'custom', 'auto'] = 'auto', cache_fname_fmt: str | ~typing.Callable[[...], str] = '{fn_name}_{checksum_hex}{suffix}', cache_fname_fmt_args: ~typing.Iterable[str] | None = None, cache_dump_fn: ~typing.Callable[[~typing.Any, ~pathlib.Path], ~typing.Any] | None = None, cache_load_fn: ~typing.Callable[[~pathlib.Path], ~typing.Any] | None = None, cache_enable: bool = True, cache_store_mode: ~typing.Literal['outputs_only', 'outputs_metadata', 'outputs_metadata_inputs'] = 'outputs_only') Callable[source]

Decorator to store function output in a cache file.

Cache file is identified by the checksum of the function arguments, and stored by default in “~/.cache/disk_cache/<Function_name>/” directory.

Example

>>> import pythonwrench as pw
>>> @pw.disk_cache_decorator
>>> def heavy_processing():
>>>     # Lot of stuff here
>>>     ...
>>> outputs = heavy_processing()  # first time function is called
>>> outputs = heavy_processing()  # second time outputs is loaded from disk
Args:

fn: Function to store its output. By default, it must be a callable that returns a pickable object. cache_dpath: Cache directory path. defaults to “~/.cache/disk_cache”. cache_force: Force function call and overwrite cache. defaults to False. cache_verbose: Set verbose logging level. Higher means more verbose. defaults to 0. cache_checksum_fn: Checksum function to identify input arguments. defaults to pythonwrench.checksum_any. cache_saving_backend: Optional saving backend. Can be one of (‘csv’, ‘json’, ‘pickle’, ‘custom’, ‘auto’). defaults to ‘auto’. cache_fname_fmt: Cache filename format. defaults to “{fn_name}_{checksum_hex}{suffix}”. cache_dump_fn: Dump/save function to store outputs and overwrite saving backend. defaults to None. cache_load_fn: Load function to store outputs and overwrite saving backend. defaults to None. cache_enable: Enable disk cache. If False, the function has no effect. defaults to True. cache_store_mode: Disk cache storage mode. By default, it store function output and saved date into the cache file. defaults to ‘outputs_metadata’.

pythonwrench.dump_csv(data: Iterable[Mapping[str, Any]] | Mapping[str, Iterable[Any]] | Iterable, file: str | Path | PathLike | TextIOBase | None = None, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, header: bool | 'auto' = 'auto', align_content: bool = False, replace_newline_by: str | None = '\\n', **csv_writer_kwds) str[source]

Dump content to CSV format into string and/or file.

Args:

data: Data to serialize. Can be a list of dicts, dicts of lists or list of lists. file: File path or buffer to write serialized data. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. header: Indicates if CSV must have header. If “auto”, an header is added when a dict of list or list of dicts is passed. defaults to “auto”. align_content: If True, center content at the middle of each row for better visualization. defaults to False. replace_newline_by: Replace newline character to avoid newline in CSV content. defaults to “\n”. **csv_writer_kwds: Others optional arguments passed to CSV writer object.

Returns:

Dumped content as string.

pythonwrench.dump_dict(dic: Mapping[str, T] | None = None, /, join: str = ', ', fmt: str = '{key}={value}', ignore_lst: Iterable[T] = (), **kwargs) str[source]

Dump dictionary of scalars to string function to customize representation.

Example 1:

>>> d = {"a": 1, "b": 2}
>>> dump_dict(d)
... 'a=1, b=2'
pythonwrench.dump_json(data: Any, file: str | Path | None | TextIOBase = None, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, indent: int | None = 4, ensure_ascii: bool = False, **json_dumps_kwds) str[source]

Dump content to JSON format into a string and/or file.

Args:

data: Data to dump to JSON. file: Optional filepath to save dumped data. Not used if None. defaults to None. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. indent: JSON indentation size in spaces. defaults to 4. ensure_ascii: Ensure only ASCII characters. defaults to False. **json_dump_kwds: Other args passed to json.dumps.

Returns:

Dumped content as string.

pythonwrench.dump_jsonl(data: list, file: str | Path | None | TextIOBase = None, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, ensure_ascii: bool = False, **json_dumps_kwds) str[source]

Dump content to JSONL format into a string and/or file.

Args:

data: Data to dump to JSONL. file: Optional filepath to save dumped data. Not used if None. defaults to None. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. ensure_ascii: Ensure only ASCII characters. defaults to False. **json_dump_kwds: Other args passed to json.dumps.

Returns:

Dumped content as string.

pythonwrench.dump_pickle(data: Any, file: str | Path | PathLike | BinaryIO | None = None, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, **pkl_dumps_kwds) bytes[source]

Dump content to PICKLE format into bytes and/or file.

Args:

data: Data to dump to PICKLE. file: Optional filepath to save dumped data. Not used if None. defaults to None. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. **pkl_dumps_kwds: Other args passed to pickle.dumps.

Returns:

Dumped content as bytes.

pythonwrench.dumps_csv(data: Iterable[Mapping[str, Any]] | Mapping[str, Iterable[Any]] | Iterable, /, *, to_builtins: bool = False, header: bool | 'auto' = 'auto', align_content: bool = False, replace_newline_by: str | None = '\\n', **csv_writer_kwds) str[source]

Dump content to CSV format into string.

Args:

data: Data to serialize. Can be a list of dicts, dicts of lists or list of lists. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. header: Indicates if CSV must have header. If “auto”, an header is added when a dict of list or list of dicts is passed. defaults to “auto”. align_content: If True, center content at the middle of each row for better visualization. defaults to False. replace_newline_by: Replace newline character to avoid newline in CSV content. defaults to “\n”. **csv_writer_kwds: Others optional arguments passed to CSV writer object.

Returns:

Dumped content as string.

pythonwrench.dumps_json(data: Any, /, *, to_builtins: bool = False, indent: int | None = 4, ensure_ascii: bool = False, **json_dumps_kwds) str[source]
pythonwrench.dumps_jsonl(data: list, /, *, to_builtins: bool = False, ensure_ascii: bool = False, **json_dumps_kwds) str[source]
pythonwrench.dumps_pickle(data: Any, /, *, to_builtins: bool = False, **pkl_dumps_kwds) bytes[source]

Dump content to PICKLE format into bytes.

Args:

data: Data to dump to PICKLE. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. **pkl_dumps_kwds: Other args passed to pickle.dumps.

Returns:

Dumped content as bytes.

pythonwrench.duplicate_list(lst: list[T], sizes: list[int]) list[T][source]

Duplicate elements elements of a list with the corresponding sizes.

Example

>>> lst = ["a", "b", "c", "d", "e"]
>>> sizes = [1, 0, 2, 1, 3]
>>> duplicate_list(lst, sizes)
... ["a", "c", "c", "d", "e", "e", "e"]
pythonwrench.filter_and_call(fn: Callable[[...], T], **kwargs: Any) T[source]

Call object only with the valid keyword arguments. Non-valid arguments are ignored.

Examples

>>> def f(x, y):
>>>     return x + y
>>> filter_and_call(f, y=2, x=1)
... 3
>>> filter_and_call(f, y=2, x=1, z=0)  # z is ignored
... 3
pythonwrench.filter_iterable(it: ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_T], include: ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_T] | None = None, exclude: ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_T] | None = None, *, match_fn: ~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__V_T, __SPHINX_IMMATERIAL_TYPE_VAR__V_T], bool] = <built-in function eq>, order: ~typing.Literal['left', 'right'] = 'right') list[T][source]
pythonwrench.filter_with_patterns(x: ~typing.Iterable[str], include: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern] | None = '.*', *, exclude: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern] | None = (), match_fn: ~typing.Callable[[str | ~re.Pattern, str], ~typing.Any] = <function search>) list[str][source]
pythonwrench.find(target: ~typing.Any, it: ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_V], *, match_fn: ~typing.Callable[[~typing.Any, ~typing.Any], bool] = <built-in function eq>, order: ~typing.Literal['left', 'right'] = 'right', default: __SPHINX_IMMATERIAL_TYPE_VAR__V_U = -1, return_value: bool = False) int | U | tuple[int | U, V | U][source]
pythonwrench.find_closest_in_list(x: str, lst: ~typing.Iterable[str], sim_fn: ~typing.Callable[[str, str], float] = <function sequence_matcher_ratio>, higher_is_closer: bool = True) str | None[source]

Find closest element in a list based on matches ratio.

pythonwrench.find_patterns(x: str, patterns: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern], *, match_fn: ~typing.Callable[[str | ~re.Pattern, str], ~typing.Any] = <function search>, default: __SPHINX_IMMATERIAL_TYPE_VAR__V_T = -1) int | T[source]

Find index of a pattern that match the first argument. If no pattern matches, returns the default value (-1).

pythonwrench.flat_dict_of_dict(nested_dic: Mapping[str, Any], *, sep: str = '.', flat_iterables: bool = False, overwrite: bool = True) dict[str, Any][source]

Flat a nested dictionary.

Example 1

>>> dic = {
...     "a": 1,
...     "b": {
...         "a": 2,
...         "b": 10,
...     },
... }
>>> flat_dict_of_dict(dic)
... {"a": 1, "b.a": 2, "b.b": 10}

Example 2

>>> dic = {"a": ["hello", "world"], "b": 3}
>>> flat_dict_of_dict(dic, flat_iterables=True)
... {"a.0": "hello", "a.1": "world", "b": 3}
Args:

nested_dic: Nested mapping containing sub-mappings or iterables. sep: Separators between keys. flat_iterables: If True, flat iterable and use index as key. overwrite: If True, overwrite duplicated keys in output. Otherwise duplicated keys will raises a ValueError.

pythonwrench.flat_list_of_list(lst: Iterable[Sequence[T]], return_sizes: bool = True) tuple[list[T], list[int]] | list[T][source]

Return a flat version of the input list of sublists with each sublist size.

pythonwrench.flatten(x: ~typing.Any, start_dim: int = 0, end_dim: int | None = None, is_scalar_fn: ~typing.Callable[[~typing.Any], ~typing.TypeGuard[__SPHINX_IMMATERIAL_TYPE_VAR__V_T]] | ~typing.Callable[[~typing.Any], ~typing.TypeIs[__SPHINX_IMMATERIAL_TYPE_VAR__V_T]] = <function is_builtin_scalar>) list[Any][source]
pythonwrench.function_alias(alternative: Callable[[P], U]) Callable[[...], Callable[[P], U]][source]

Decorator to wrap function aliases.

Example

>>> def f(a: int, b: str) -> str:
>>>    return a * b
>>> @function_alias(f)
>>> def g(*args, **kwargs): ...
>>> f(2, "a")
... "aa"
>>> g(3, "b")  # calls function f() internally.
... "bbb"
pythonwrench.get_argnames(fn: Callable) list[str][source]

Get arguments names of a method, function or callable object. This function does not return the ‘self’ argument for methods.

pythonwrench.get_current_file_logger(*, parent_deep: int = 1, default: __SPHINX_IMMATERIAL_TYPE_VAR__V_T = <RootLogger root (WARNING)>) Logger | T[source]

Returns the logger of the caller file. If this cannot be found, returns the root logger.

pythonwrench.get_current_fn_name(*, default: T = '') str | T[source]

Get caller function name.

pythonwrench.get_defaults_values(obj: DataclassInstance) dict[str, Any][source]
pythonwrench.get_fullname(x: Any, *, inst_suffix: str = '(...)') str[source]

Returns the classname of an object with parent modules.

Args:

obj: Object to scan. inst_suffix: Suffix appended to the classname in case the object is an instance of a class.

Examples

>>> get_fullname([0, 1, 2])
... 'builtins.list(...)'
>>> get_fullname(1.0)
... 'builtins.float(...)'
>>> class A: def f(self): return 0
>>> a = A()
>>> get_fullname(a)
... '__main__.A(...)'
>>> get_fullname(A)
... '__main__.A'
>>> get_fullname(a.f)
... '__main__.A.f'
>>> get_fullname(A.f)
... '__main__.A.f'
pythonwrench.get_ipython_name() 'TerminalInteractiveShell' | 'ZMQInteractiveShell' | None[source]
pythonwrench.get_key_fn(patterns: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern], *, match_fn: ~typing.Callable[[str | ~re.Pattern, str], ~typing.Any] = <function search>) Callable[[str], int][source]

Generate key_fn to sorted list of string using multiple patterns.

Example

>>> lst = ["a", "abc", "aa", "abcd"]
>>> patterns = ["^ab"]  # sort list with elements starting with 'ab' first
>>> list(sorted(lst, key=get_key_fn(patterns)))
... ["abc", "abcd", "a", "aa"]
pythonwrench.get_now(fmt: str = '%Y-%m-%dT%H:%M:%S') str[source]

Returns current datetime as string with the specified format.

pythonwrench.get_now_iso8601() str[source]

Returns current datetime as string with the ISO8601 format.

pythonwrench.get_null_logger() Logger[source]
pythonwrench.get_num_cpus_available() int[source]

Returns the number of CPUs available for the current process on Linux-based platforms.

On Windows and MAC OS, this will just return the number of logical CPUs on this machine. If the number of CPUs cannot be detected, returns 0.

pythonwrench.hash_file(fpath: str | Path | BufferedReader, hash_type: 'sha256' | 'md5' | Hasher = 'md5', chunk_size: int | None = 268435456) str[source]

Return the hash value for a file.

Based on https://github.com/pytorch/audio/blob/v0.13.0/torchaudio/datasets/utils.py#L110

Args:

fpath: Path to existing file. hash_type: Hash name or custom Hasher algorithm. chunk_size: Max chunk size in bytes. defaults to 268435456 (256 MiB).

Returns:

Hash value as string.

pythonwrench.identity(x: T, **kwargs) T[source]

Identity function placeholder. Returns the first argument. Other keywords arguments are ignored.

pythonwrench.intersect(*args, start=None)[source]

Reduce elements using “and” operator (&).

pythonwrench.intersect_lists(lst_of_lst: Sequence[Iterable[T]]) list[T][source]

Performs intersection of elements in lists (like set intersection), but keep their original order.

pythonwrench.is_available_package(package: str) bool[source]

Returns True if package is installed in the current python environment.

pythonwrench.is_builtin_collection(x: Any, *, strict: bool = False) TypeIs[list | tuple | dict | set | frozenset][source]

Returns True if x is an instance of a builtin collection type (list, tuple, dict, set, frozenset).

Args:

x: Object to check. strict: If True, it will not consider custom subtypes of builtins as builtin collections. defaults to False.

pythonwrench.is_builtin_number(x: Any, *, strict: bool = False) TypeIs[bool | int | float | complex][source]

Returns True if x is an instance of a builtin number type (int, float, bool, complex).

Args:

x: Object to check. strict: If True, it will not consider custom subtypes of builtins as builtin numbers. defaults to False.

pythonwrench.is_builtin_obj(x: Any) bool[source]

Returns True if object is an instance of a builtin object.

Note: If the object is an instance of a custom subtype of a builtin object, this function returns False.

pythonwrench.is_builtin_scalar(x: Any, *, strict: bool = False) TypeIs[bool | int | float | complex | None | str | bytes][source]

Returns True if x is an instance of a builtin scalar type (int, float, bool, complex, NoneType, str, bytes).

Args:

x: Object to check. strict: If True, it will not consider subtypes of builtins as builtin scalars. defaults to False.

pythonwrench.is_dataclass_instance(x: Any) TypeIs[DataclassInstance][source]

Returns True if argument is a dataclass.

Unlike function dataclasses.is_dataclass, this function returns False for a dataclass type.

pythonwrench.is_editable_package(package: str) bool[source]

Returns True if package is installed in editable mode in the current python environment.

pythonwrench.is_full(it: Iterable[T], eq_fn: Callable[[T, T], bool] | None = None) bool[source]

Returns true if all elements in iterable are equal.

Note: This function returns True for iterable that contains 0 or 1 element.

pythonwrench.is_iterable_bool(x: Any, *, accept_generator: bool = True) TypeIs[Iterable[bool]][source]
pythonwrench.is_iterable_bytes_or_list(x: Any, *, accept_generator: bool = True) TypeIs[Iterable[bytes | list]][source]
pythonwrench.is_iterable_float(x: Any, *, accept_generator: bool = True) TypeIs[Iterable[float]][source]
pythonwrench.is_iterable_int(x: Any, *, accept_bool: bool = True, accept_generator: bool = True) TypeIs[Iterable[int]][source]
pythonwrench.is_iterable_integral(x: Any, *, accept_generator: bool = True) TypeIs[Iterable[Integral]][source]
pythonwrench.is_iterable_str(x: Any, *, accept_str: bool = True, accept_generator: bool = True) TypeGuard[Iterable[str]][source]
pythonwrench.is_namedtuple_instance(x: Any) TypeIs[NamedTupleInstance][source]

Returns True if argument is a NamedTuple.

pythonwrench.is_sequence_str(x: Any, *, accept_str: bool = True) TypeGuard[Sequence[str]][source]
pythonwrench.is_sorted(x: Iterable[Any], *, reverse: bool = False, strict: bool = False) bool[source]
pythonwrench.is_typed_dict(x: Any) TypeGuard[type][source]
pythonwrench.is_unique(it: Iterable[T], ne_fn: Callable[[T, T], bool] | None = None, use_set: bool = False) bool[source]

Returns true if all elements in iterable are differents.

Note: This function returns True for iterable that contains 0 or 1 element.

pythonwrench.isinstance_generic(obj: Any, class_or_tuple: type[T] | None | tuple[type[T], ...] | Any, *, check_only_first: bool = False) TypeIs[T][source]

Improved isinstance(…) function that supports parametrized Union, TypedDict, Literal, Mapping or Iterable.

Args:

obj: Object to check. class_or_tuple: Type to check. Can be a parametrized type from typing. check_only_first: If True, check only if first element when checking for Iterable[type]. defaults to False.

Example 1

>>> isinstance_generic({"a": 1, "b": 2}, dict)
... True
>>> isinstance_generic({"a": 1, "b": 2}, dict[str, int])
... True
>>> isinstance_generic({"a": 1, "b": 2}, dict[str, str])
... False
>>> from typing import Literal
>>> isinstance_generic({"a": 1, "b": 2}, dict[str, Literal[1, 2]])
... True
pythonwrench.list_dict_to_dict_list(lst: ~typing.Iterable[~typing.Mapping[__SPHINX_IMMATERIAL_TYPE_VAR__V_K, __SPHINX_IMMATERIAL_TYPE_VAR__V_V]], key_mode: ~typing.Literal['intersect', 'same', 'union'] | ~typing.Iterable[__SPHINX_IMMATERIAL_TYPE_VAR__V_K] = 'same', default_val: __SPHINX_IMMATERIAL_TYPE_VAR__V_W = None, *, default_val_fn: ~typing.Callable[[__SPHINX_IMMATERIAL_TYPE_VAR__V_K], __SPHINX_IMMATERIAL_TYPE_VAR__V_X] | None = None, list_fn: ~typing.Callable[[~typing.List[__SPHINX_IMMATERIAL_TYPE_VAR__V_V | __SPHINX_IMMATERIAL_TYPE_VAR__V_W | __SPHINX_IMMATERIAL_TYPE_VAR__V_X]], __SPHINX_IMMATERIAL_TYPE_VAR__V_Y] | None = <function identity>) dict[K, Y][source]

Convert list of dicts to dict of lists.

Args:

lst: The list of dict to merge. Cannot be a Generator. key_mode: Can be “same” or “intersect”. - If “same”, all the dictionaries must contains the same keys otherwise a ValueError will be raised. - If “intersect”, only the intersection of all keys will be used in output. - If “union”, the output dict will contains the union of all keys, and the missing value will use the argument default_val. - If an iterable of elements, use them as keys for output dict. default_val: Default value of an element when key_mode is “union”. defaults to None. default_val_fn: Function to return the default value according to a specific key. defaults to None. list_fn: Optional function to build the values. defaults to identity.

pythonwrench.load_csv(file: str | Path | TextIOBase, /, *, orient: 'list' | 'dict' = 'list', header: bool = True, comment_start: str | None = None, strip_content: bool = False, delimiter: str | None = ',', **csv_reader_kwds) list[dict[str, Any]] | dict[str, list[Any]][source]

Load content from csv filepath.

Args:

orient: Orientation of the output value. Can be “list” or “dict”. defaults to “list”. header: Specify if CSV has header column. defaults to True. comment_start: If this string is not None and a line starts with this string, the line will be ignored. defaults to None. delimiter: Value delimiter. defaults to “,”. **csv_reader_kwds: Other optional csv arguments.

Returns:

The loaded values as dict of lists, list of dicts or list of lists.

pythonwrench.load_json(file: str | Path | PathLike | TextIOBase, /, **json_loads_kwds) Any[source]
pythonwrench.load_jsonl(file: str | Path | PathLike | TextIOBase, /, **json_loads_kwds) list[source]
pythonwrench.load_pickle(file: str | Path | BinaryIO, /, **pkl_loads_kwds) Any[source]

Load content from PICKLE file.

Args:

file: Filepath file path. **pkl_loads_kwds: Other args passed to pickle.loads.

pythonwrench.loads_csv(content: str, /, *, orient: 'list' | 'dict' = 'list', header: bool = True, comment_start: str | None = None, strip_content: bool = False, delimiter: str | None = ',', **csv_reader_kwds) list[dict[str, Any]] | dict[str, list[Any]][source]
pythonwrench.loads_json(content: str, /, **json_loads_kwds) Any[source]
pythonwrench.loads_jsonl(content: str, /, **json_loads_kwds) list[source]
pythonwrench.loads_pickle(content: bytes, /, **pkl_loads_kwds) Any[source]

Load content from raw bytes.

Args:

content: Encoded elements bytes. **pkl_loads_kwds: Other args passed to pickle.loads.

pythonwrench.log_once(msg: str, logger: str | ModuleType | None | Logger | '__parent_file__' | SupportsIterLen[str | ModuleType | None | Logger | '__parent_file__'] = '__parent_file__', *, level: int = 20) None[source]

Log message to loggers at the specified level.

pythonwrench.match_patterns(x: str, include: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern] | None = '.*', *, exclude: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern] | None = (), match_fn: ~typing.Callable[[str | ~re.Pattern, str], ~typing.Any] = <function search>) bool[source]

Returns True if the first argument match at least 1 included pattern and does not match any excluded pattern.

Args:

x: String to check. include: Acceptable pattern(s) for x. If None, match all patterns with ‘.*’. defaults to ‘.*’. exclude: Forbidden pattern(s) for x. If None, match no patterns with value (). defaults to (). match_fn: Match function use to compare a pattern with argument x. defaults to re.search.

pythonwrench.parse_to(target_type: type[T], *, case_sensitive: bool = False, true_values: str | Iterable[str] = ('True', 't', 'yes', 'y', '1'), false_values: str | Iterable[str] = ('False', 'f', 'no', 'n', '0'), none_values: str | Iterable[str] = ('None', 'null')) Callable[[str], T][source]

Returns a callable that convert string value to target type safely.

Intended for argparse arguments.

pythonwrench.prod(*args, start: Any = 1)[source]

Compute product of elements.

pythonwrench.randstr(low_or_size: int = 10, high: int | None = None, /, *, letters: Iterable[str] = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', seed: int | None = None) str[source]

Returns a randomly generated string of a random range length.

pythonwrench.read_csv(file: str | Path | TextIOBase, /, *, orient: 'list' | 'dict' = 'list', header: bool = True, comment_start: str | None = None, strip_content: bool = False, delimiter: str | None = ',', **csv_reader_kwds) list[dict[str, Any]] | dict[str, list[Any]][source]

Load content from csv filepath.

Args:

orient: Orientation of the output value. Can be “list” or “dict”. defaults to “list”. header: Specify if CSV has header column. defaults to True. comment_start: If this string is not None and a line starts with this string, the line will be ignored. defaults to None. delimiter: Value delimiter. defaults to “,”. **csv_reader_kwds: Other optional csv arguments.

Returns:

The loaded values as dict of lists, list of dicts or list of lists.

pythonwrench.read_json(file: str | Path | PathLike | TextIOBase, /, **json_loads_kwds) Any[source]
pythonwrench.read_jsonl(file: str | Path | PathLike | TextIOBase, /, **json_loads_kwds) Any
pythonwrench.read_pickle(file: str | Path | BinaryIO, /, **pkl_loads_kwds) Any[source]

Load content from PICKLE file.

Args:

file: Filepath file path. **pkl_loads_kwds: Other args passed to pickle.loads.

pythonwrench.recursive_generator(x: Any) Generator[tuple[Any, int, int], None, None][source]
pythonwrench.reduce_add(*args, start=None)[source]

Reduce elements using “add” operator (+).

pythonwrench.reduce_and(*args, start=None)[source]

Reduce elements using “and” operator (&).

pythonwrench.reduce_mul(*args, start=None)[source]

Reduce elements using “mul” operator (*).

pythonwrench.reduce_or(*args, start=None)[source]

Reduce elements using “or” operator (|).

pythonwrench.register_as_builtin_fn(class_or_tuple: type | tuple[type, ...] | None = None, *, custom_predicate: Predicate | None = None, priority: int = 0) Callable[source]

Decorator to add an as_builtin function.

Example

>>> import numpy as np
>>> @register_as_builtin_fn(np.ndarray)
>>> def my_checksum_for_numpy(x: np.ndarray):
>>>     return x.tolist()
>>> pw.as_builtin([np.array([1, 2]), [3, 4]])
... [[1, 2], [3, 4]]
pythonwrench.register_checksum_fn(class_or_tuple: type | tuple[type, ...] | None = None, *, custom_predicate: Predicate | None = None, priority: int = 0) Callable[source]

Decorator to add a checksum function.

Example

>>> import numpy as np
>>> @register_checksum_fn(np.ndarray)
>>> def my_checksum_for_numpy(x: np.ndarray):
>>>     return int(x.sum())
>>> pw.checksum_any(np.array([1, 2]))  # calls my_checksum_for_numpy internally, even if array in nested inside a list, dict, etc.
pythonwrench.reload_editable_packages(*, verbose: int = 0) list[ModuleType][source]

Reload all submodules of editable packages already imported.

pythonwrench.reload_submodules(*modules: ModuleType, verbose: int = 0, only_editable: bool = True, only_loaded: bool = False) list[ModuleType][source]

Reload all submodule recursively.

pythonwrench.repeat_fn(f: Callable[[T], T], n: int) Callable[[T], T][source]

Creates wrapper which call a function n items.

pythonwrench.running_on_interpreter() bool[source]
pythonwrench.running_on_notebook() bool[source]
pythonwrench.running_on_terminal() bool[source]
pythonwrench.safe_rmdir(root: str | Path, *, rm_root: bool = True, error_on_non_empty_dir: bool = True, followlinks: bool = False, dry_run: bool = False, verbose: int = 0) tuple[list[str], list[str]][source]

Remove all empty sub-directories.

Args:

root: Root directory path. rm_root: If True, remove the root directory too if it is empty at the end. defaults to True. error_on_non_empty_dir: If True, raises a RuntimeError if a subdirectory contains at least 1 file. Otherwise it will ignore non-empty directories. defaults to True. followlinks: Indicates whether or not symbolic links shound be followed. defaults to False. dry_run: If True, does not remove any directory and just output the list of directories which could be deleted. defaults to False. verbose: Verbose level. defaults to 0.

Returns:

A tuple containing the list of directories paths deleted and the list of directories paths reviewed.

pythonwrench.save_csv(data: Iterable[Mapping[str, Any]] | Mapping[str, Iterable[Any]] | Iterable, file: str | Path | PathLike | TextIOBase, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, header: bool | 'auto' = 'auto', align_content: bool = False, replace_newline_by: str | None = '\\n', **csv_writer_kwds) None[source]

Save content to CSV format into a file or buffer.

Args:

data: Data to serialize. Can be a list of dicts, dicts of lists or list of lists. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. header: Indicates if CSV must have header. If “auto”, an header is added when a dict of list or list of dicts is passed. defaults to “auto”. align_content: If True, center content at the middle of each row for better visualization. defaults to False. replace_newline_by: Replace newline character to avoid newline in CSV content. defaults to “\n”. **csv_writer_kwds: Others optional arguments passed to CSV writer object.

pythonwrench.save_json(data: Any, file: str | Path | PathLike | TextIOBase, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, indent: int | None = 4, ensure_ascii: bool = False, **json_dumps_kwds) None[source]
pythonwrench.save_jsonl(data: list, file: str | Path | PathLike | TextIOBase, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, ensure_ascii: bool = False, **json_dumps_kwds) None[source]
pythonwrench.save_pickle(data: Any, file: str | Path | PathLike | BinaryIO, /, *, overwrite: bool = True, make_parents: bool = True, to_builtins: bool = False, **pkl_dumps_kwds) None[source]

Dump content to PICKLE format into file.

Args:

data: Data to dump to PICKLE. file: Filepath to save dumped data. overwrite: If True, overwrite target filepath. defaults to True. make_parents: Build intermediate directories to filepath. defaults to True. to_builtins: If True, converts data to builtin equivalent before saving. defaults to False. **pkl_dumps_kwds: Other args passed to pickle.dumps.

pythonwrench.search_submodules(root: ModuleType, only_editable: bool = True, only_loaded: bool = False) list[ModuleType][source]

Return the submodules already imported.

pythonwrench.sequence_matcher_ratio(a: str, b: str) float[source]

Compute distance ratio of two strings.

pythonwrench.setup_logging_level(package_or_logger: str | ModuleType | None | Logger | '__parent_file__' | SupportsIterLen[str | ModuleType | None | Logger | '__parent_file__'] = None, level: int | None = 20, *, fmt: str | None | Formatter = '[%(asctime)s][%(name)s][%(levelname)s] - %(message)s', stream: IO[str] | 'auto' = 'auto', set_fmt: bool = True, capture_warnings: bool = True, autoreload: bool = True) None[source]

Helper function to customize logging messages using logging.level.

Note: Lower level values means more debug messages.

pythonwrench.setup_logging_verbose(package_or_logger: str | ModuleType | None | Logger | '__parent_file__' | SupportsIterLen[str | ModuleType | None | Logger | '__parent_file__'] = None, verbose: int | None = 1, *, fmt: str | None | Formatter = '[%(asctime)s][%(name)s][%(levelname)s] - %(message)s', stream: IO[str] | 'auto' = 'auto', set_fmt: bool = True, capture_warnings: bool = True, autoreload: bool = True) None[source]

Helper function to customize logging messages using verbose_level.

Note: Higher verbose values means more debug messages.

pythonwrench.shuffled(x: MutableSequence[T], *, seed: int | None = None, deep: bool = False) MutableSequence[T][source]
pythonwrench.sort_with_patterns(x: ~typing.Iterable[str], patterns: str | ~re.Pattern | ~typing.Iterable[str | ~re.Pattern], *, match_fn: ~typing.Callable[[str | ~re.Pattern, str], ~typing.Any] = <function search>, reverse: bool = False) list[str][source]
pythonwrench.sorted_dict(x: Mapping[K, V], /, *, by: 'key' | 'value' | 'item' = 'key', key: Callable[[Any], Any] | None = None, reverse: bool = False) dict[K, V][source]

Sort a dictionnary by key, value or item.

pythonwrench.str_to_bool(x: str, *, case_sensitive: bool = False, true_values: str | Iterable[str] = ('True', 't', 'yes', 'y', '1'), false_values: str | Iterable[str] = ('False', 'f', 'no', 'n', '0')) bool[source]

Convert string values to bool safely. Intended for argparse arguments.

  • True values: ‘True’, ‘T’, ‘yes’, ‘y’, ‘1’.

  • False values: ‘False’, ‘F’, ‘no’, ‘n’, ‘0’.

  • Other raises ValueError.

pythonwrench.str_to_none(x: str, *, case_sensitive: bool = False, none_values: str | Iterable[str] = ('None', 'null')) None[source]

Convert string values to None safely. Intended for argparse arguments.

  • None values: ‘None’, ‘null’

  • Other raises ValueError.

pythonwrench.str_to_optional_bool(x: str, *, case_sensitive: bool = False, true_values: str | Iterable[str] = ('True', 't', 'yes', 'y', '1'), false_values: str | Iterable[str] = ('False', 'f', 'no', 'n', '0'), none_values: str | Iterable[str] = ('None', 'null')) bool | None[source]

Convert string values to optional bool safely. Intended for argparse arguments.

  • True values: ‘True’, ‘T’, ‘yes’, ‘y’, ‘1’.

  • False values: ‘False’, ‘F’, ‘no’, ‘n’, ‘0’.

  • None values: ‘None’, ‘null’

  • Other raises ValueError.

pythonwrench.str_to_optional_float(x: str, *, case_sensitive: bool = False, none_values: str | Iterable[str] = ('None', 'null')) float | None[source]

Convert string values to optional float safely. Intended for argparse arguments.

pythonwrench.str_to_optional_int(x: str, *, case_sensitive: bool = False, none_values: str | Iterable[str] = ('None', 'null')) int | None[source]

Convert string values to optional int safely. Intended for argparse arguments.

pythonwrench.str_to_optional_str(x: str, *, case_sensitive: bool = False, none_values: str | Iterable[str] = ('None', 'null')) str | None[source]

Convert string values to optional str safely. Intended for argparse arguments.

pythonwrench.str_to_type(x: str, target_type: type[T], *, case_sensitive: bool = False, true_values: str | Iterable[str] = ('True', 't', 'yes', 'y', '1'), false_values: str | Iterable[str] = ('False', 'f', 'no', 'n', '0'), none_values: str | Iterable[str] = ('None', 'null')) T[source]

Convert string values to target type safely. Intended for argparse arguments.

  • True values: ‘True’, ‘T’, ‘yes’, ‘y’, ‘1’.

  • False values: ‘False’, ‘F’, ‘no’, ‘n’, ‘0’.

  • None values: ‘None’, ‘null’

  • Other raises ValueError.

pythonwrench.sum(*args, start: Any = 0)[source]

Compute sum of elements.

pythonwrench.tree_iter(root: str | Path, *, include: str | Pattern | Iterable[str | Pattern] = '.*', exclude: str | Pattern | Iterable[str | Pattern] = (), space: str = ' ', branch: str = '│ ', tee: str = '├── ', last: str = '└── ', max_depth: int = 9223372036854775807, followlinks: bool = False, skipfiles: bool = False, sort: bool = False) Generator[str, Any, None][source]

A recursive generator, given a directory Path object will yield a visual tree structure line by line with each line prefixed by the same characters

Based on: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python

pythonwrench.unflat_dict_of_dict(dic: Mapping[str, Any], *, sep: str = '.') dict[str, Any][source]

Unflat a dictionary.

Example 1

>>> dic = {
    "a.a": 1,
    "b.a": 2,
    "b.b": 3,
    "c": 4,
}
>>> unflat_dict_of_dict(dic)
... {"a": {"a": 1}, "b": {"a": 2, "b": 3}, "c": 4}
pythonwrench.unflat_list_of_list(flatten_lst: Sequence[T], sizes: Iterable[int]) list[list[T]][source]

Unflat a list to a list of sublists of given sizes.

pythonwrench.union(*args, start=None)[source]

Reduce elements using “or” operator (|).

pythonwrench.union_dicts(dicts: Iterable[dict[K, V]]) dict[K, V][source]

Performs union of dictionaries.

pythonwrench.union_lists(lst_of_lst: Iterable[Iterable[K]]) list[K][source]

Performs union of elements in lists (like set union), but keep their original order.

pythonwrench.unzip(lst)[source]

Invert function of builtin zip().

Example

>>> lst1 = [1, 2, 3, 4]
>>> lst2 = [5, 6, 7, 8]
>>> zipped_list = list(zip(lst1, lst2))
>>> zipped_list
... [(1, 5), (2, 6), (3, 7), (4, 8)]
>>> unzip(zipped_list)
... [1, 2, 3, 4], [5, 6, 7, 8]
pythonwrench.warn_once(message: str | Warning, category: type[Warning] | None = None, stacklevel: int = 1, source: Any = None) None[source]

Warn message once using warnings module.

Subpackages

Submodules