serhii.net

In the middle of the desert you can say anything you want

18 Nov 2021

211118-0024 python namedtuple

Python’s NamedTuple is really cool!

Python’s Instance, Class, and Static Methods Demystified – Real Python is an excellent guide, as is the entire website.

NamedTuple VS Dataclass, copying from SO answer:[^1] When your data structure needs to/can be immutable, hashable, iterable, unpackable, comparable then you can use NamedTuple. If you need something more complicated, for example, a possibility of inheritance for your data structure then use Dataclass.

The immutable part is important - can’t do named_tuple.value = 3 after creating it.

Can be created also through colections.namedtuple, copied directly from :

>>> from collections import namedtuple

>>> Person = namedtuple("Person", "name children")
>>> john = Person("John Doe", ["Timmy", "Jimmy"])
>>> john
Person(name='John Doe', children=['Timmy', 'Jimmy'])
>>> id(john.children)
139695902374144
Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus