Using named tuples

An alternative to dictionaries in Python is namedtuple. As the name implies, a named tuple is a tuple where each entry can be accessed via a name instead of being accessed via its index. The benefits of using named tuples instead of dictionaries are the following:

  • Named tuples fields can be accessed with their field names and dot notation: foo.x allows us to access the x field of the foo tuple.
  • Named tuples are as efficient as tuples. Accessing a field of a tuple is much faster than a field of a dictionary. With a dictionary, each field is accessed via its hash value, and a lookup is necessary for each access to a dictionary field. This is not the case with tuples and named tuples. Their fields are immediately accessible. So, creating and using them is more efficient.
  • Named tuples, as with tuples, are immutable. This is also a good property for functional and reactive code where object lifetimes are very short, and they should not be modified.

Named tuples are implemented in the collections module of the standard library. Before being used, a named tuple must be declared. Once it is declared, it can be used like a class constructor. Here is the previous code snippet with dictionaries being replaced with namedtuple:

from collections import namedtuple

Basket = namedtuple('Basket', ['count', 'what'])
FruitCount = namedtuple('FruitCount', ['count', 'double'])

obs = Observable.from_([Basket(count=5, what='apple'),
Basket(count=3, what='orange')])
.filter(lambda i: i.what == 'apple')
.map(lambda i: i.count)
.map(lamda i: FruitCount(count=i, double=i*2))
...

This simple change makes the code simpler. All the quotes, square brackets, colons, and curly braces have disappeared. The constructor style notation to create the objects, and the dot style notation to access the fields, is simpler to follow.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.184.200