making a variable available in a function from decorator

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 30 08:15:48 CEST 2007


En Sun, 29 Jul 2007 19:22:47 -0300, rkmr.em at gmail.com <rkmr.em at gmail.com>  
escribió:

> I create a variable in a decorator. i want to be able to access that
> variable in the function to be decorated. How to do this?

Combining `wraps` and `partial` from the functools standard module  
<http://docs.python.org/lib/module-functools.html>:

import functools

def my_decorator(f):
     newvar = 1234 # compute your desired variable
     @functools.wraps(f)
     def wrapper(*args, **kwds):
       print "Calling", f.func_name
       return f(*args, **kwds)
     return functools.partial(wrapper, newvar=newvar)

@my_decorator
def foo(x,y,**kw):
   print "x=",x,"y=",y
   # access the variable as a keyword argument
   if "newvar" in kw:
     print "newvar",kw["newvar"]

py> foo(1,2)
Calling foo
x= 1 y= 2
newvar 1234

-- 
Gabriel Genellina




More information about the Python-list mailing list