what is a function object?

Michael Hudson mwh21 at cam.ac.uk
Tue Nov 9 22:42:59 CET 1999


zakons at my-deja.com writes:

> Hi,
> I use function objects for sorting lists and they are great but I want
> to know more about what a function object is in the python environment.

Well, in one way, a function isn't really much different from an
integer or an instance of a class or any other Python object; they're
builtin objects so you can't derive from them, etc.
 
> * How is a function object different from other python objects? What
> does it include extra? What is missing?

Well, they're of type types.FunctionType. This means that when you try
and call one the interpreter notices that it is a function and does
the right thing.

> * How may function objects be accessed by name in various namespaces?

Exactly as any other data type.

With one caveat: if a function is residing in the __dict__ of a class
object and you access it via . notation, it is automagically wrapped
up into a method object.

> * Other than for sorting, what are typical uses of function objects?

Hmm, passing as arguments to map, callbacks into various libraries,
... oh and calling them.

y'see when the interpreter sees 

     foo(x)

it doesn't know a priori that the name "foo" is bound to a
function. So it looks the name "foo" up, and assuming it finds
something, attempts to call it with argument x. "Attempting to call
it" goes something like:

if type(foo) is types.MethodType:
     apply(foo.im_func,(foo.im_self,x))
elif type(foo) is types.FunctionType:
     apply(foo,(x,))
elif hasattr(foo,'__call__'):
     apply(foo.__call__,(x,))

builtins complicate the above, but I hope you get the idea.

> * What does it mean to say that function objects are first-class
> objects in the python environment?

That you can pass the as arguments, return them from functions and
store them in variables as with any other data type.

> Thanks,
> Stuart Zakon
> Objects by Design
> www.objectsbydesign.com

I hope that helped.
Michael




More information about the Python-list mailing list