Existence of mutable named tuple in Python? Existence of mutable named tuple in Python? python python

Existence of mutable named tuple in Python?


There is a mutable alternative to collections.namedtuplerecordclass.It can be installed from PyPI:

pip3 install recordclass

It has the same API and memory footprint as namedtuple and it supports assignments (It should be faster as well). For example:

from recordclass import recordclassPoint = recordclass('Point', 'x y')>>> p = Point(1, 2)>>> pPoint(x=1, y=2)>>> print(p.x, p.y)1 2>>> p.x += 2; p.y += 3; print(p)Point(x=3, y=5)

recordclass (since 0.5) support typehints:

from recordclass import recordclass, RecordClassclass Point(RecordClass):   x: int   y: int>>> Point.__annotations__{'x':int, 'y':int}>>> p = Point(1, 2)>>> pPoint(x=1, y=2)>>> print(p.x, p.y)1 2>>> p.x += 2; p.y += 3; print(p)Point(x=3, y=5)

There is a more complete example (it also includes performance comparisons).

Recordclass library now provides another variant -- recordclass.make_dataclass factory function.

recordclass and make_dataclass can produce classes, whose instances occupy less memory than __slots__-based instances. This is can be important for the instances with attribute values, which has not intended to have reference cycles. It may help reduce memory usage if you need to create millions of instances. Here is an illustrative example.


types.SimpleNamespace was introduced in Python 3.3 and supports the requested requirements.

from types import SimpleNamespacet = SimpleNamespace(foo='bar')t.ham = 'spam'print(t)namespace(foo='bar', ham='spam')print(t.foo)'bar'import picklewith open('/tmp/pickle', 'wb') as f:    pickle.dump(t, f)


As a Pythonic alternative for this task, since Python-3.7, you can usedataclasses module that not only behaves like a mutable NamedTuple, because they use normal class definitions they also support other classes features.

From PEP-0557:

Although they use a very different mechanism, Data Classes can be thought of as "mutable namedtuples with defaults". Because Data Classes use normal class definition syntax, you are free to use inheritance, metaclasses, docstrings, user-defined methods, class factories, and other Python class features.

A class decorator is provided which inspects a class definition for variables with type annotations as defined in PEP 526, "Syntax for Variable Annotations". In this document, such variables are called fields. Using these fields, the decorator adds generated method definitions to the class to support instance initialization, a repr, comparison methods, and optionally other methods as described in the Specification section. Such a class is called a Data Class, but there's really nothing special about the class: the decorator adds generated methods to the class and returns the same class it was given.

This feature is introduced in PEP-0557 that you can read about it in more details on provided documentation link.

Example:

In [20]: from dataclasses import dataclassIn [21]: @dataclass    ...: class InventoryItem:    ...:     '''Class for keeping track of an item in inventory.'''    ...:     name: str    ...:     unit_price: float    ...:     quantity_on_hand: int = 0    ...:     ...:     def total_cost(self) -> float:    ...:         return self.unit_price * self.quantity_on_hand    ...:    

Demo:

In [23]: II = InventoryItem('bisc', 2000)In [24]: IIOut[24]: InventoryItem(name='bisc', unit_price=2000, quantity_on_hand=0)In [25]: II.name = 'choco'In [26]: II.nameOut[26]: 'choco'In [27]: In [27]: II.unit_price *= 3In [28]: II.unit_priceOut[28]: 6000In [29]: IIOut[29]: InventoryItem(name='choco', unit_price=6000, quantity_on_hand=0)