Namedtuple Python container

Create the new type

To create a new named tuple pass a valid identifier and a list of strings representing the properties name.

from collection import namedtuple
Mytype = namedtuple("Type", ["field1", "field2"])

Note that named tuples are immutable, but the values they store may not.

Instantiate and access properties

myvar = Mytype(1, 2)

a = myvar.field1
b = myvar.field2

Class properties can be accessed with the usual indexing as well:

a = myvar[0]
b = myvar[1]

Additional attributes and methods

The ._replace() method allows to update the value of a given field (actually, it creates a new named tuple instance instead of updating the instance in place).

Named tuples can be converted into dictionaries with the ._asdict() method, which returns a dictionary with the field names as keys.

The ._fields attribute holds a tuple listing the field names.


© Alessandro Dotti Contra :: VAT # IT03617481209 :: This site uses no cookies, read our privacy policy for more information.