Skip to content

helpers

Miscellaneous helper functions.

dump(obj)

Dumps all pydantic models in an arbitrary object to dicts. As a side effect iterables are all downcast to lists. Useful when models exist in e.g. a list.

Parameters:

Name Type Description Default
obj Any

The object to dump.

required

Returns:

Type Description
Any

tp.Any: The dumped object.

Source code in watz/helpers.py
def dump(
    obj: tp.Any,
) -> tp.Any:
    """Dumps all pydantic models in an arbitrary object to dicts. As a side effect iterables are all downcast to lists. Useful when models exist in e.g. a list.

    Args:
        obj: The object to dump.

    Returns:
        tp.Any: The dumped object.
    """
    if isinstance(obj, BaseModel):
        return dump(obj.model_dump())

    if isinstance(obj, dict):
        return {dump(key): dump(value) for key, value in obj.items()}

    if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
        return [dump(item) for item in obj]

    return obj

serialize(obj)

A wrapper on orjson.dumps() to include all configuration options for handling all supported types.

Parameters:

Name Type Description Default
obj Any

The object to serialize to json.

required

Returns:

Name Type Description
bytes bytes

The serialized json bytes blob.

Source code in watz/helpers.py
def serialize(obj: tp.Any) -> bytes:
    """A wrapper on `orjson.dumps()` to include all configuration options for handling all supported types.

    Args:
        obj: The object to serialize to json.

    Returns:
        bytes: The serialized json bytes blob.
    """
    return orjson.dumps(
        obj,
        option=orjson.OPT_SERIALIZE_NUMPY
        | orjson.OPT_SERIALIZE_DATACLASS
        | orjson.OPT_SERIALIZE_UUID
        | orjson.OPT_NAIVE_UTC,  # Make dts without timezone info default to UTC
        # Fallback to the python func on types orjson doesn't support:
        default=_orjson_extras,
    )

Last update: October 19, 2023
Created: October 19, 2023