functions which take functions

Terry Reedy tjreedy at udel.edu
Mon Apr 9 16:34:52 EDT 2012


On 4/9/2012 2:57 PM, Kiuhnm wrote:
> Do you have some real or realistic (but easy and self-contained)
> examples when you had to define a (multi-statement) function and pass it
> to another function?

This is so common in Python that it is hardly worth sneezing about.

map(f, iterable)
filter(f, iterable)
functools.wraps(f, args)

---
Sometimes it is a bit hidden.

@deco
def f(): pass

is equivalent to

def f(): pass # replace with multiple statements
f = deco(f)

In fact, one reason for moving the wrapper above the def line is that 
function bodies can be arbitrarily large, moving the explicit call 
arbitrarily far away.

---
class C():
     def test(self): print(self, '.test called')

c = C()
c.test()
import types
types.MethodType(c.__class__.test, c)()
# This *is* the internal implementation of c.test

#prints
<__main__.C object at 0x000000000363E278> .test called
<__main__.C object at 0x000000000363E278> .test called

----
In numerical analysis, functions that numerically integrate, 
differentiate, regress, fit, or plot functions take functions as arguments.

---
The most common, so common you do not notice it, is passing functions to 
other functions via the global namespace that is the hidden argument to 
all functions. (Every function has a readonly .__globals__ attribute 
that is used to resolve global accesses.)

def g(): pass
def h(): pass
def j(a): return g(h(a))

Be glad you do not have to *always* do something like

def j(a, funcs): return funcs.g(funcs.h(a))
print(j(a, locals()))

-- 
Terry Jan Reedy




More information about the Python-list mailing list