Named Tuples

Python 2.6 module collections introduces the namedtuple datatype. The factory function namedtuple (typename, fieldnames) creates subclasses of tuple whose fields are accessible by name as well as index:

# Create a named tuple class 'person':

person = collections.namedtuple('person', 'name firstName age') # field names separated by space or comma assert issubclass(person, tuple)

assert person._fields == ('name', 'firstName', 'age')

# Create an instance of person: jdoe = person('Doe', 'John', 30)

assert str(jdoe) == "person(name='Doe', firstName='John', age=30)"

assert jdoe[0] == == 'Doe' # access by index or name i s equivalent assert jdoe[2] == jdoe.age == 30

# Convert instance to dict:

assert jdoe._asdi ct() == {'age': 30, 'name': 'Doe', 'firstName': 'John'}

# Although tuples are normally immutable, one can change field values via _replace(): jdoe._replace(age=25, firstName='Jane')

assert str(jdoe) == "person(name='Doe', firstName='Jane', age=2 5)"

Was this article helpful?

0 0

Post a comment