Passing Functions
The concept of function pointers is an advanced topic when learning a language such as C, but not Python where functions are like any other object. They can be referenced (accessed or aliased to other variables), passed as arguments to functions, be elements of container objects like lists and dictionaries, etc. The one unique characteristic of functions which may set them apart from other objects is that they are callable, i.e., can be invoked via the function operator.
functions can be aliases to other variables. Because all objects are passed by reference, functions are no different. When assigning to another variable, you are assigning the reference to the same object; and if that object is a function, then all aliases to that same object are invokable:
>>> def foo(): … print 'in foo()' … >>> bar = foo >>> bar() in foo()
When we assigned foo to bar, we are assigning the same function object to bar, thus we can invoke bar() in the same way we call foo(). Be sure you understand the difference between “foo” (reference of the function object) and “foo()” (invocation of the function object). Taking our reference example a bit further, we can even pass functions in as arguments to other functions for invocation:
>>> def bar(argfunc): argfunc() >>> bar(foo) in foo()
Note that it is the function object foo that is being passed to bar().bar() is the function that actually calls foo() (which has been aliased to the local variable argfunc in the same way that we assigned foo to bar in the previous example).