[Tutor] Python functions are first-class citizens

Ben Finney ben+python at benfinney.id.au
Fri Aug 1 08:46:38 CEST 2014


memilanuk <memilanuk at gmail.com> writes:

> On 07/31/2014 08:22 PM, Ben Finney wrote:
> >> max_key = max(counts, key=counts.get)
> >
> > This specifies ‘counts.get’, without calling it. The expression
> > ‘counts.get’ evaluates to that function object.
> >
> > That value is then used as the value for the ‘key’ parameter when
> > calling ‘max’ here.
>
> Been reading a bit more in the mean time, trying to grok that 'key'
> parameter for max()... and of course the python docs for max(iterable,
> key=) refer to the docs for list.sort() ;)

The ‘max’ function can be told how to determine the ordering of items,
by specifying a key parameter. The parameter is specified by giving a
value; that value is a function.

The ‘max’ implementation uses the ‘key’ parameter by calling it. So in
this way, you can specify any behaviour you like, by making a function
that determines ordering however you like.

Generally, though, there are existing functions you can use; and a
dictionary's ‘get’ method is one of them.

This is all intentional, and is why the fact functions are first-class
in Python is such a strength.

> So counts is the iterable

More accurately, it is a collection. Whether it is iterable isn't
relevant to ‘max’.

> and counts.get is the key used to iterate through it?

No, ‘max’ does not necessarily iterate; it computes (in whatever way
makes sense) which item is the largest. You're specifying how items are
to be compared. Iteration is irrelevant to this.

> Where things are going pear-shaped is how counts.get can function as a
> key' when we don't actually supply () (or anything inside them) to
> specify what k,v pair we want, and how that relates back to the
> iterable for max(), counts?

A function is itself a value. That may take a little thinking to get
your head around, but all of this merely follows as a consequence.

You may also need to spend time distinguishing between syntax and value.
‘foo’ and ‘foo()’ are different in their syntax; when evaluated in an
expression, they have entirely different meanings. But the latter
differs only in that an extra function call occurs before evaluating the
result.

-- 
 \     “God was invented to explain mystery. God is always invented to |
  `\     explain those things that you do not understand.” —Richard P. |
_o__)                                                    Feynman, 1988 |
Ben Finney



More information about the Tutor mailing list