Python higher-order function to get named attributes
Python High-Order Functions for Named Attributes Let’s look at a slightly different data set. Let’s assume we’re using a subclass of NamedTuple
instead of an anonymous tuple object. First, define a class that provides the following type hints for the two items in the tuple.
from typing import NamedTuple
class YearCheese(NamedTuple):
year: int
cheese: float
Then we convert the underlying data year_cheese
into a suitable named tuple. The conversion process is as follows:
>>> year_cheese_2 = list(YearCheese(*yc) for yc in year_cheese)
>>> year_cheese_2
[YearCheese(year=2000, cheese=29.87),
YearCheese(year=2001, cheese=30.12),
YearCheese(year=2002, cheese=30.6),
YearCheese(year=2003, cheese=30.66),
YearCheese(year=2004, cheese=31.33),
YearCheese(year=2005, cheese=32.62),
YearCheese(year=2006, cheese=32.73),
YearCheese(year=2007, cheese=33.5), YearCheese(year=2008, cheese=32.84),
YearCheese(year=2009, cheese=33.02),
YearCheese(year=2010, cheese=32.92)]
There are two ways to determine the range of cheese consumption: you can use the attrgetter()
function as shown below, or you can use the anonymous function form.
>>> from operator import attrgetter
>>> min(year_cheese_2, key=attrgetter('cheese'))
YearCheese(year=2000, cheese=29.87)
>>> max(year_cheese_2, key=lambda x: x.cheese)
YearCheese(year=2007, cheese=33.5)
The key point here is that with the anonymous function object, the attribute name is a token in the code, while with the attrgetter()
function, the attribute name is a string. Using a string makes the attribute name a parameter that can be modified during script execution, making the program more flexible.