Skip to content

Utils

Utilities.

generic_id_generator(id_func)

Parameterized ID generator.

Source code in src/snailz/utils.py
14
15
16
17
18
19
20
def generic_id_generator(id_func):
    """Parameterized ID generator."""

    current = 0
    while True:
        current += 1
        yield id_func(current)

json_dump(obj, indent=2)

Dump as JSON with appropriate settings.

Parameters:

Name Type Description Default
obj

The object to serialize

required
indent

Indentation (None for none)

2

Returns:

Type Description

String representation of object.

Source code in src/snailz/utils.py
23
24
25
26
27
28
29
30
31
32
33
34
def json_dump(obj, indent=2):
    """Dump as JSON with appropriate settings.

    Parameters:
        obj: The object to serialize
        indent: Indentation (None for none)

    Returns:
        String representation of object.
    """

    return json.dumps(obj, indent=indent, default=_serialize_json)

_serialize_json(obj)

Custom JSON serializer for JSON conversion.

Parameters:

Name Type Description Default
obj

The object to serialize

required

Returns:

Type Description

String representation of date objects or dict for Pydantic models;

None for PIL images.

Raises:

Type Description
TypeError

If the object type is not supported for serialization

Source code in src/snailz/utils.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def _serialize_json(obj):
    """Custom JSON serializer for JSON conversion.

    Parameters:
        obj: The object to serialize

    Returns:
        String representation of date objects or dict for Pydantic models;
        None for PIL images.

    Raises:
        TypeError: If the object type is not supported for serialization
    """
    if isinstance(obj, date):
        return obj.isoformat()
    if isinstance(obj, BaseModel):
        return obj.model_dump()
    if isinstance(obj, PilImage):
        return None
    raise TypeError(f"Type {type(obj)} not serializable")