Tutorial using namedtuples in Python

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Instead of using a tuple, consider using a namedtuple instead, which is more self-documenting.

Consider this function apply_color() which accepts a tuple of three values (which should be the red, green, and blue components of a color)…

To access the three color component values, we had to do rgb[0], rgb[1], and rgb[2]. Furthermore, we have to remember which one is red, green, and blue.

To use namedtuples we import from collections, we can write more descriptively like this …

We did not change the function apply_color. It still expects a three value tuple like before. And it still accesses the tuple value via indices like before. You can use a named tuple where-ever you can use a tuple.

However, if you like, you can re-write the apply_color() to use the namedtuple form …

In this case, you must pass it a namedtuple of Color; otherwise it will not know what rgb.green is.

When defining the namedtuple, the second parameter is a space separated string which the function will parse. However, it works just as well if you pass it a list or tuple instead…


Related Posts

Tags

Share This