Skip to content

Utils

Utilities.

generic_id_generator(id_func)

Parameterized ID generator.

Parameters:

Name Type Description Default
id_func callable

function to generate a single ID

required

Returns:

Type Description
generator

ID generator.

Source code in src/snailz/utils.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def generic_id_generator(id_func):
    """Parameterized ID generator.

    Parameters:
        id_func (callable): function to generate a single ID

    Returns:
        (generator): 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 any

The object to serialize

required
indent int | None

Indentation (None for none)

2

Returns:

Type Description
str

JSON representation of object.

Source code in src/snailz/utils.py
30
31
32
33
34
35
36
37
38
39
40
41
def json_dump(obj, indent=2):
    """Dump as JSON with appropriate settings.

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

    Returns:
        (str): JSON representation of object.
    """

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

max_grid_value(grids)

Find maximum value across a list of grids.

Source code in src/snailz/utils.py
44
45
46
47
48
49
50
51
52
def max_grid_value(grids):
    """Find maximum value across a list of grids."""

    result = 0.0
    for g in grids:
        for x in range(g.size):
            for y in range(g.size):
                result = max(result, g[x, y])
    return result

_serialize_json(obj)

Custom JSON serializer for JSON conversion.

Parameters:

Name Type Description Default
obj any

The object to serialize

required

Returns:

Type Description
str | None

string representation or None.

Raises:

Type Description
TypeError

If the object type is not supported for serialization

Source code in src/snailz/utils.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def _serialize_json(obj):
    """Custom JSON serializer for JSON conversion.

    Parameters:
        obj (any): The object to serialize

    Returns:
        (str | None): string representation or None.

    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")