Skip to content

Utils

utils

Additional utilities that fit nowhere else.

KT = TypeVar('KT') module-attribute

PT = TypeVar('PT', bound=BaseModel) module-attribute

T = TypeVar('T') module-attribute

VT = TypeVar('VT') module-attribute

EmptyListError

Custom exception for an empty list in SList.

MultipleItemsError

Custom exception for a list with multiple items in SList.

SList

A list that holds often only a single element.

item() -> T

convert_md_to_py(path: Path | str, *, target_path: Path | str | None = None) -> None

Converts a Markdown file to a py file by extracting all python codeblocks

Parameters:

Name Type Description Default
path Path | str

Path to the Markdown file to convert

required
target_path Path | str | None

Path to save the new Python file. If not provided, the new file will be the same file with .py

None

Warning

If a file with the same name already exists, it will be overwritten.

deepcopy_with_sharing(obj: Any, shared_attributes: Sequence[str], memo: dict[int, Any] | None = None)

Like deepcopy but specified attributes are shared.

Deepcopy an object, except for a given list of attributes, which should be shared between the original object and its copy.

Parameters:

Name Type Description Default
obj Any

some object to copy

required
shared_attributes Sequence[str]

A list of strings identifying the attributes that should be shared instead of copied.

required
memo dict[int, Any] | None

dictionary passed into deepcopy. Ignore this argument if not calling from within deepcopy.

None

Example

class A(object):
    def __init__(self):
        self.copy_me = []
        self.share_me = []

    def __deepcopy__(self, memo):
        return deepcopy_with_sharing(
            self, shared_attribute_names=['share_me'], memo=memo
        )


a = A()
b = deepcopy(a)
assert a.copy_me is not b.copy_me
assert a.share_me is b.share_me

c = deepcopy(b)
assert c.copy_me is not b.copy_me
assert c.share_me is b.share_me

Original from https://stackoverflow.com/a/24621200

del_nested_attr(obj: PT, attr_paths: str | Sequence[str] | None, *, inplace: bool = False, missing_ok: bool = False) -> PT

Remove nested attributes from an object.

dict_diff(dct1: Mapping[KT, VT], dct2: Mapping[KT, VT]) -> tuple[list[KT], list[KT], dict[KT, tuple[VT, VT]]]

Returns the added keys, removed keys and keys of changed values of both dictionaries.

dict_diff_str(dct1: Mapping[KT, VT], dct2: Mapping[KT, VT]) -> tuple[str, str, str]

Returns the added keys, removed keys and keys of changed values of both dictionaries as strings for printing.

find_index(elem: Any, lst: list[Any]) -> int | None

Find the index of the element in the list or return None.

find_indices(elements: np.ndarray | Sequence[Any], total_set: np.ndarray | Sequence[Any]) -> np.ndarray

Finds the indices of the elements in the total set.

flatten(nested_list: Sequence[Sequence[T]]) -> list[T]

Flatten a nested list.

is_dt_str(dt_str: str) -> bool

Check if the given string is a valid datetime string.

is_notebook() -> bool

Determine if we are running within a Jupyter notebook.

is_stable_release() -> bool

Return whether the current version is a stable release.

is_stable_version(version_str: str) -> bool

Return whether the given version is a stable release.

parse_dt_str(dt_str: str) -> pnd.DateTime | pnd.Date | pnd.Interval

Parse a string to a pendulum object using the local timezone if none provided or UTC otherwise.

rank(arr: np.ndarray) -> np.ndarray

Returns the rank of the elements in the array and gives the same rank to equal elements.

safe_list_get(lst: Sequence[T], idx: int, *, default: T | None = None) -> T | None

Get the element at the index of the list or return the default value.

store_retvals(func)

Decorator storing the return values as function attribute for later cleanups.

This can be used for instance in a generator like this:

@pytest.fixture
def create_blank_db(notion, test_area):
    @store_retvals
    def nested_func(db_name):
        db = notion.databases.create(
            parent=test_area,
            title=db_name,
            schema={
                'Name': schema.Title(),
            },
        )
        return db

    yield nested_func

    # clean up by deleting the db of each prior call
    for db in nested_func.retvals:
        notion.databases.delete(db)

str_hash(*args: str, n_chars: int = 16) -> str

Hashes string arguments to a n-character string.

temp_attr(obj: object, **kwargs: Any) -> Generator[None, None, None]

Temporarily sets multiple attributes of an object to specified values, and restores their original values after the context exits.

Parameters:

Name Type Description Default
obj object

The object whose attributes will be modified.

required
**kwargs Any

The attributes and their temporary values to modify.

{}

temp_timezone(tz: str | pnd.Timezone)

Temporarily set the local timezone to the given timezone. Mostly used by unit tests.

to_pendulum(dt_spec: str | dt.datetime | dt.date | pnd.Interval) -> pnd.DateTime | pnd.Date | pnd.Interval

Convert a datetime or date object to a pendulum object.