function wrappers

Paul Hankin paul.hankin at gmail.com
Wed Oct 10 08:23:06 EDT 2007


On Oct 10, 11:39 am, Ramon Crehuet <rcs... at iiqab.csic.es> wrote:
> Dear all,
> I have a Fortran programming background and I have some difficulties in
> understading how function wrappers work. I have delved into the subject
> because of the new decorators, but I understand the decorator syntax. My
> ignorance is more profound... Here is an example without decorators:

Functions are first-class values: this means they can be passed
around, used in expressions, and returned from other functions in just
the same way that ints, floats and other more obvious types.

All a decorator is a function that takes the function you give it, and
returns a new function. In your 'require_int' example, it returns the
nested function 'wrapper'. The clever bit is that 'wrapper' remembers
the argument to the decorator - func - (with value p1 in your
example), and can call it later.

Think of the 'def' statement as constructing an object which happens
to be a function. It has a dictionary which is used for variable
lookup so that it can remember 'func'. The def statement also binds
this function object to a name: the name of the function. You can see
some of the gory details if you go:

def f():
   print 42

dir(f)

... list of attributes of the function object.

--
Paul Hankin




More information about the Python-list mailing list