collections.namedtuple

Shortcut For Simple Data-Holding Classes

  • Much writing for a simple data holder

    class Person:
        def __init__(self, firstname, lastname):
            self.firstname = firstname
            self.lastname = lastname
    
    person = Person('Joerg', 'Faschingbauer')
    print(person.firstname, person.lastname)
    
    Joerg Faschingbauer
    
  • Written shorter (and with much more features - but read on)

    from collections import namedtuple
    Person = namedtuple('Person', ('firstname', 'lastname'))
    
    person = Person('Joerg', 'Faschingbauer')
    print(person.firstname, person.lastname)
    
    Joerg Faschingbauer
    

Constructing From Iterable: _make()

  • Data-holding classes are popular with tabular data (CSV, databases, …)

  • Rows are iterable

  • someclass._make()

  • Example: rows read from a CSV file

    persons_from_csv = [
        ['Joerg', 'Faschingbauer'],
        ['Caro', 'Faschingbauer'],
    ]
    
  • Turning each into a Person object

    for person in map(Person._make, persons_from_csv):
        print(person.firstname, person.lastname)
    
    Joerg Faschingbauer
    Caro Faschingbauer
    

Convert To dict: _asdict()

person = Person('Joerg', 'Faschingbauer')
person_dict = person._asdict()
person_dict
{'firstname': 'Joerg', 'lastname': 'Faschingbauer'}