Utils - Snailz Docs

Skip to content

# Utils

Snailz utilities.

## `fail(msg)`

Report failure and exit.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`msg` | `str` | Error message to display | required

Source code in `src/snailz/utils.py`

    31
    32
    33
    34
    35
    36
    37
    38
    def fail(msg: str) -> None:
        """Report failure and exit.

        Parameters:
            msg: Error message to display
        """
        print(msg, file=sys.stderr)
        sys.exit(1)

## `json_dump(obj)`

Dump as JSON with appropriate settings.

Source code in `src/snailz/utils.py`

    41
    42
    43
    def json_dump(obj: BaseModel) -> str:
        """Dump as JSON with appropriate settings."""
        return json.dumps(obj, indent=2, default=_serialize_json)

## `report(verbose, msg)`

Report if verbosity turned on.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`verbose` | `bool` | Is display on or off? | required
`msg` | `str` | Message to display | required

Source code in `src/snailz/utils.py`

    46
    47
    48
    49
    50
    51
    52
    53
    54
    def report(verbose: bool, msg: str) -> None:
        """Report if verbosity turned on.

        Parameters:
            verbose: Is display on or off?
            msg: Message to display
        """
        if verbose:
            print(msg)

## `sigmoid(x)`

Calculate sigmoid curve value for x in 0..1.

Sigmoid parameters are chosen so that s(0)=0, s(0.5)=0.5, and s(1)=1.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`x` | `float` | input value | required

Returns:

Type | Description
--- | ---
`float` | Sigmoid curve value.

Source code in `src/snailz/utils.py`

    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    def sigmoid(x: float) -> float:
        """Calculate sigmoid curve value for x in 0..1.

        Sigmoid parameters are chosen so that s(0)=0, s(0.5)=0.5, and s(1)=1.

        Parameters:
            x: input value

        Returns:
            Sigmoid curve value.
        """
        a = 16.0
        b = 0.5
        c = -0.0002
        return 1 / (1 + math.exp(-a * (x - b))) + c

## `to_csv(rows, fields, f_make_row)`

Generic converter from list of models to CSV string.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`rows` | `list` | List of rows to convert. | required
`fields` | `list` | List of names of columns. | required
`f_make_row` | `Callable` | Function that converts a row to text. | required

Returns:

Type | Description
--- | ---
`str` | CSV representation of data.

Source code in `src/snailz/utils.py`

    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    def to_csv(rows: list, fields: list, f_make_row: Callable) -> str:
        """Generic converter from list of models to CSV string.

        Parameters:
            rows: List of rows to convert.
            fields: List of names of columns.
            f_make_row: Function that converts a row to text.

        Returns:
            CSV representation of data.
        """

        output = io.StringIO()
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow(fields)
        for r in rows:
            writer.writerow(f_make_row(r))
        return output.getvalue()

## `unique_id(name, func, limit=UNIQUE_ID_LIMIT)`

Generate unique IDs.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`name` | `str` | name of this generator | required
`func` | `Callable` | function to generate next candidate | required
`limit` | `int` | how many tries per ID | `UNIQUE_ID_LIMIT`

Returns:

Type | Description
--- | ---
`None` | Unique ID.

Source code in `src/snailz/utils.py`

     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    def unique_id(
        name: str, func: Callable, limit: int = UNIQUE_ID_LIMIT
    ) -> Generator[str, tuple | None, None]:
        """Generate unique IDs.

        Parameters:
            name: name of this generator
            func: function to generate next candidate
            limit: how many tries per ID

        Returns:
            Unique ID.
        """
        gen = _make_unique_id_generator(name, func, limit)
        next(gen)  # prime the generator
        return gen

## `_make_unique_id_generator(name, func, limit)`

Create and prime a unique ID generator.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`name` | `str` | name of this generator | required
`func` | `Callable` | function to generate next candidate | required
`limit` | `int` | how many tries per ID | required

Returns:

Type | Description
--- | ---
`None` | Unique ID.

Source code in `src/snailz/utils.py`

    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    def _make_unique_id_generator(
        name: str, func: Callable, limit: int
    ) -> Generator[str, tuple | None, None]:
        """Create and prime a unique ID generator.

        Parameters:
            name: name of this generator
            func: function to generate next candidate
            limit: how many tries per ID

        Returns:
            Unique ID.
        """
        seen = set()
        provided = yield ""  # to prime the generator
        while True:
            found = False
            for _ in range(limit):
                if provided is None:
                    provided = ()
                temp = func(*provided)
                assert isinstance(temp, str)
                if temp in seen:
                    continue
                seen.add(temp)
                found = True
                break
            if not found:
                raise RuntimeError(f"{name} unable to find unique ID")
            provided = yield temp

## `_serialize_json(obj)`

Custom JSON serializer for JSON conversion.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`obj` | `object` | The object to serialize | required

Returns:

Type | Description
--- | ---
`str | dict` | String representation of date objects or dict for Pydantic models

Raises:

Type | Description
--- | ---
`TypeError` | If the object type is not supported for serialization

Source code in `src/snailz/utils.py`

    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    def _serialize_json(obj: object) -> str | dict:
        """Custom JSON serializer for JSON conversion.

        Parameters:
            obj: The object to serialize

        Returns:
            String representation of date objects or dict for Pydantic models

        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()
        raise TypeError(f"Type {type(obj)} not serializable")