Skip to content

Container utils

💻 API reference

opt_dict

Bases: dict[K, V], _ConverterProtocol

Source code in fateful/container.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class opt_dict(dict[K, V], _ConverterProtocol):
    """ """

    def __init__(self, *args: t.Any, **kwargs: t.Any):
        super().__init__(*args, **kwargs)
        for k, v in self.items():
            self[k] = self._convert(v)

    def stringify(self, *args: t.Any, **kwargs: t.Any) -> str:
        r: str | bytes = json.dumps(self, *args, **kwargs)
        if isinstance(r, bytes):
            return r.decode("utf-8")
        return r

    def map_to(self, clazz: type[T]) -> T:
        """expected a dataclass or a pydantic basemodel"""
        return clazz(**self)

    def maybe(self, item: K) -> Some[V] | Empty:
        try:
            value = super().__getitem__(item)
        except KeyError:
            return none
        else:
            return Some(self._convert(value))

    def __getattr__(self, item: str) -> Some[V] | Empty:
        return self.maybe(t.cast(K, item))

    def __setattr__(self, key: str, value: V) -> None:
        self[t.cast(K, key)] = value

    def __str__(self) -> str:
        return f"<opt_dict {super().__str__()} >"

map_to(clazz)

expected a dataclass or a pydantic basemodel

Source code in fateful/container.py
82
83
84
def map_to(self, clazz: type[T]) -> T:
    """expected a dataclass or a pydantic basemodel"""
    return clazz(**self)

opt_list

Bases: list[T], _ConverterProtocol

Immutable wrapper around a list that converts all dicts to JsObjects and all lists to JsArrays.

Parameters:

Name Type Description Default
list _type_

description

required
x = opt_list([1,2,3])
v: Some[int] = x.at(0)
z: Empty = x.at(12)
Source code in fateful/container.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class opt_list(list[T], _ConverterProtocol):
    """
    Immutable wrapper around a list that converts all dicts to JsObjects and
    all lists to JsArrays.

    Args:
        list (_type_): _description_

    ```python
    x = opt_list([1,2,3])
    v: Some[int] = x.at(0)
    z: Empty = x.at(12)
    ```
    """

    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
        super().__init__(*args, **kwargs)
        for i in range(len(self)):
            self[i] = self._convert(self[i])

    def at(self, index: int) -> Some[T] | Empty:
        try:
            item = super().__getitem__(index)
        except IndexError:
            return none
        else:
            return Some(self._convert(item))

    def __iter__(self) -> Iterator[T]:
        for item in super().__iter__():
            yield self._convert(item)

    def __str__(self) -> str:
        return f"<opt_list {super().__str__()} >"