[Tutor] Accessing Functions By Reference

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 21 19:18:43 CEST 2004



On Thu, 21 Oct 2004, Lloyd Kvam wrote:

> somefunction is a reference to the function
> somefunction() calls the function.
>
> a = somefunction	# binds the name a to the function
> a()	# calls the function
>
> I've usually seen the ability to process functions using variables (i.e.
> just another form of data) described as having "first class functions".


Hi John,


Here's a classic example of a "first class" function:

###
>>> def compose(f, g):
...     """Given functions f and g, returns a new function that
...     takes an x and calls f(g(x))."""
...     def newFunction(x):
...         return f(g(x))
...     return newFunction
...
###


Now we have a way of "composing" functions together:

###
>>> f = compose(str.split, str.upper)
>>> f("hello world this is a test")
['HELLO', 'WORLD', 'THIS', 'IS', 'A', 'TEST']
>>>
>>> def square(x):
...     return x * x
...
>>> def sqrt(x):
...     return x ** (0.5)
...
>>> abs = compose(sqrt, square)
>>> abs(-42)
42.0
>>> abs(17)
17.0
###


So yes, Python does make it convenient to treat functions as values: they
can be passed around to other functions, and returned as values.


Hope this helps!



More information about the Tutor mailing list