function wrappers

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Oct 10 13:27:35 EDT 2007


Scott David Daniels a écrit :
> Ramon Crehuet wrote:
>> def require_int(func):
>>       def wrapper(arg):
>>           assert isinstance(arg, int)
>>           return func(arg)
>>       return wrapper
>> def p1(a):
>>   print a
>> p2 = require_int(p1)
>>
>> My question is: why do p2 arguments become wrapper arguments? What is 
>> the flux of the arguments in the program when you pass functions as 
>> arguments?

> I suspect you don't understand that each time require_int is called
> a _new_ function named wrapper is created 

which remembers the 'environnement' in which it was defined - this is 
known as a 'closure'.

> (and then returned).

And when this wrapper function is called (instead of the original), it 
receives the arg, test it, and if approriate delegate call to the 
original (wrapped) function.

Another way (perhaps easier to understand if you don't have any 
experience with higher order functions and other functional programming 
idioms) to get the same result would be:

class require_int(object):
   def __init__(self, func):
     self._func = func
   def __call__(self, arg):
     assert isinstance(arg, int)
     return self._func(arg)



More information about the Python-list mailing list