Skip to content

NamedTuple

This module contains the implementation of the NamedTuple class.

NamedTuple class imitates the behavior of the named tuple.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.x
10
>>> nt.z
KeyError
>>> len(nt)
2
>>> nt.keys()
["x", "y"]
>>> nt.values()
[10, "Hello"]
>>> nt.has_key("x")
True
>>> nt.has_key("z")
False
>>> nt.has_value(10)
True
>>> nt.has_value([1, 2, 3])
False
>>> nt.get("x")
10
>>> nt.get("z")
None
>>> nt.update("z", [1, 2, 3])
KeyError
>>> d = nt.to_dict()
>>> d["x"]
10
>>> nt["z"] = [1, 2, 3]
TypeError
>>> nt.update("x", 20)
>>> nt.x
20
>>> nt.x = 20
Error: AttributeDoesNotSetValue
>>> del nt.x
Error: AttributeCannotBeDelete

NamedTuple

This class imitates the behavior of the named tuple.

Source code in src\xloft\namedtuple.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 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
102
103
104
105
106
107
108
109
110
111
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
class NamedTuple:
    """This class imitates the behavior of the _named tuple_."""

    VAR_NAME_FOR_KEYS_LIST: str = "_jWjSaNy1RbtQinsN_keys"

    def __init__(self, **kwargs: dict[str, Any]) -> None:  # noqa: D107
        vnkl = self.__class__.VAR_NAME_FOR_KEYS_LIST
        self.__dict__[vnkl] = []
        for name, value in kwargs.items():
            self.__dict__[name] = value
            self.__dict__[vnkl].append(name)

    def __len__(self) -> int:
        """Get the number of elements.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> len(nt)
            2

        Returns:
            The number of elements in the tuple.
        """
        return len(self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST])

    def __getattr__(self, name: str) -> Any:
        """Getter.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.x
            10

        Args:
            name: Key name.

        Returns:
            Value of key.
        """
        return self.__dict__[name]

    def __setattr__(self, name: str, value: Any) -> None:
        """Blocked Setter."""
        raise AttributeDoesNotSetValue(name)

    def __delattr__(self, name: str) -> None:
        """Blocked Deleter."""
        raise AttributeCannotBeDelete(name)

    def get(self, key: str) -> Any:
        """Return the value for key if key is in the dictionary, else `None`.

        Args:
            key: Key name.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.get("x")
            10

        Returns:
            Value of key.
        """
        value = self.__dict__.get(key)
        if value is not None:
            return value
        return None

    def update(self, key: str, value: Any) -> None:
        """Update a value of key.

        Attention: This is an uncharacteristic action for the type `tuple`.

        Args:
            key: Key name.
            value: Value of key.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.update("x", 20)
            >>> nt.x
            20

        Returns:
            None
        """
        keys: list[str] = self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST]
        if not key in keys:
            err_msg = f"The key `{key}` is missing!"
            raise KeyError(err_msg)
        self.__dict__[key] = value

    def to_dict(self) -> dict[str, Any]:
        """Convert to the dictionary.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> d = nt.to_dict()
            >>> d["x"]
            10

        Returns:
            Dictionary with keys and values of the tuple.
        """
        attrs: dict[str, Any] = self.__dict__
        keys: list[str] = attrs[self.__class__.VAR_NAME_FOR_KEYS_LIST]
        return {key: attrs[key] for key in keys}

    def items(self) -> list[tuple[str, Any]]:
        """Return a set-like object providing a view on the NamedTuple's items.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> for key, val in nt.items():
            ...     print(f"Key: {key}, Value: {val}")
            "Key: x, Value: 10"
            "Key: y, Value: Hello"

        Returns:
            list[tuple[str, Any]]
        """
        attrs: dict[str, Any] = self.__dict__
        keys: list[str] = attrs[self.__class__.VAR_NAME_FOR_KEYS_LIST]
        return [(key, attrs[key]) for key in keys]

    def keys(self) -> list[str]:
        """Get a list of keys.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.keys()
            ["x", "y"]

        Returns:
            List of keys.
        """
        return self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST]

    def values(self) -> list[Any]:
        """Get a list of values.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.values()
            [10, "Hello"]

        Returns:
            List of values.
        """
        attrs: dict[str, Any] = self.__dict__
        keys: list[str] = attrs[self.__class__.VAR_NAME_FOR_KEYS_LIST]
        return [attrs[key] for key in keys]

    def has_key(self, key: str) -> bool:
        """Returns True if the key exists, otherwise False.

        Args:
            key: Key name.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.has_key("x")
            True

        Returns:
            True if the key exists, otherwise False.
        """
        keys: list[str] = self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST]
        return key in keys

    def has_value(self, value: Any) -> bool:
        """Returns True if the value exists, otherwise False.

        Args:
            value: Value of key.

        Examples:
            >>> from xloft import NamedTuple
            >>> nt = NamedTuple(x=10, y="Hello")
            >>> nt.has_value(10)
            True

        Returns:
            True if the value exists, otherwise False.
        """
        values = self.values()
        return value in values

__delattr__(name)

Blocked Deleter.

Source code in src\xloft\namedtuple.py
101
102
103
def __delattr__(self, name: str) -> None:
    """Blocked Deleter."""
    raise AttributeCannotBeDelete(name)

__getattr__(name)

Getter.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.x
10

Parameters:

Name Type Description Default
name str

Key name.

required

Returns:

Type Description
Any

Value of key.

Source code in src\xloft\namedtuple.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def __getattr__(self, name: str) -> Any:
    """Getter.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.x
        10

    Args:
        name: Key name.

    Returns:
        Value of key.
    """
    return self.__dict__[name]

__len__()

Get the number of elements.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> len(nt)
2

Returns:

Type Description
int

The number of elements in the tuple.

Source code in src\xloft\namedtuple.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def __len__(self) -> int:
    """Get the number of elements.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> len(nt)
        2

    Returns:
        The number of elements in the tuple.
    """
    return len(self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST])

__setattr__(name, value)

Blocked Setter.

Source code in src\xloft\namedtuple.py
97
98
99
def __setattr__(self, name: str, value: Any) -> None:
    """Blocked Setter."""
    raise AttributeDoesNotSetValue(name)

get(key)

Return the value for key if key is in the dictionary, else None.

Parameters:

Name Type Description Default
key str

Key name.

required

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.get("x")
10

Returns:

Type Description
Any

Value of key.

Source code in src\xloft\namedtuple.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def get(self, key: str) -> Any:
    """Return the value for key if key is in the dictionary, else `None`.

    Args:
        key: Key name.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.get("x")
        10

    Returns:
        Value of key.
    """
    value = self.__dict__.get(key)
    if value is not None:
        return value
    return None

has_key(key)

Returns True if the key exists, otherwise False.

Parameters:

Name Type Description Default
key str

Key name.

required

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.has_key("x")
True

Returns:

Type Description
bool

True if the key exists, otherwise False.

Source code in src\xloft\namedtuple.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def has_key(self, key: str) -> bool:
    """Returns True if the key exists, otherwise False.

    Args:
        key: Key name.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.has_key("x")
        True

    Returns:
        True if the key exists, otherwise False.
    """
    keys: list[str] = self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST]
    return key in keys

has_value(value)

Returns True if the value exists, otherwise False.

Parameters:

Name Type Description Default
value Any

Value of key.

required

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.has_value(10)
True

Returns:

Type Description
bool

True if the value exists, otherwise False.

Source code in src\xloft\namedtuple.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def has_value(self, value: Any) -> bool:
    """Returns True if the value exists, otherwise False.

    Args:
        value: Value of key.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.has_value(10)
        True

    Returns:
        True if the value exists, otherwise False.
    """
    values = self.values()
    return value in values

items()

Return a set-like object providing a view on the NamedTuple's items.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> for key, val in nt.items():
...     print(f"Key: {key}, Value: {val}")
"Key: x, Value: 10"
"Key: y, Value: Hello"

Returns:

Type Description
list[tuple[str, Any]]

list[tuple[str, Any]]

Source code in src\xloft\namedtuple.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def items(self) -> list[tuple[str, Any]]:
    """Return a set-like object providing a view on the NamedTuple's items.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> for key, val in nt.items():
        ...     print(f"Key: {key}, Value: {val}")
        "Key: x, Value: 10"
        "Key: y, Value: Hello"

    Returns:
        list[tuple[str, Any]]
    """
    attrs: dict[str, Any] = self.__dict__
    keys: list[str] = attrs[self.__class__.VAR_NAME_FOR_KEYS_LIST]
    return [(key, attrs[key]) for key in keys]

keys()

Get a list of keys.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.keys()
["x", "y"]

Returns:

Type Description
list[str]

List of keys.

Source code in src\xloft\namedtuple.py
185
186
187
188
189
190
191
192
193
194
195
196
197
def keys(self) -> list[str]:
    """Get a list of keys.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.keys()
        ["x", "y"]

    Returns:
        List of keys.
    """
    return self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST]

to_dict()

Convert to the dictionary.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> d = nt.to_dict()
>>> d["x"]
10

Returns:

Type Description
dict[str, Any]

Dictionary with keys and values of the tuple.

Source code in src\xloft\namedtuple.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def to_dict(self) -> dict[str, Any]:
    """Convert to the dictionary.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> d = nt.to_dict()
        >>> d["x"]
        10

    Returns:
        Dictionary with keys and values of the tuple.
    """
    attrs: dict[str, Any] = self.__dict__
    keys: list[str] = attrs[self.__class__.VAR_NAME_FOR_KEYS_LIST]
    return {key: attrs[key] for key in keys}

update(key, value)

Update a value of key.

Attention: This is an uncharacteristic action for the type tuple.

Parameters:

Name Type Description Default
key str

Key name.

required
value Any

Value of key.

required

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.update("x", 20)
>>> nt.x
20

Returns:

Type Description
None

None

Source code in src\xloft\namedtuple.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def update(self, key: str, value: Any) -> None:
    """Update a value of key.

    Attention: This is an uncharacteristic action for the type `tuple`.

    Args:
        key: Key name.
        value: Value of key.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.update("x", 20)
        >>> nt.x
        20

    Returns:
        None
    """
    keys: list[str] = self.__dict__[self.__class__.VAR_NAME_FOR_KEYS_LIST]
    if not key in keys:
        err_msg = f"The key `{key}` is missing!"
        raise KeyError(err_msg)
    self.__dict__[key] = value

values()

Get a list of values.

Examples:

>>> from xloft import NamedTuple
>>> nt = NamedTuple(x=10, y="Hello")
>>> nt.values()
[10, "Hello"]

Returns:

Type Description
list[Any]

List of values.

Source code in src\xloft\namedtuple.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def values(self) -> list[Any]:
    """Get a list of values.

    Examples:
        >>> from xloft import NamedTuple
        >>> nt = NamedTuple(x=10, y="Hello")
        >>> nt.values()
        [10, "Hello"]

    Returns:
        List of values.
    """
    attrs: dict[str, Any] = self.__dict__
    keys: list[str] = attrs[self.__class__.VAR_NAME_FOR_KEYS_LIST]
    return [attrs[key] for key in keys]