making a variable available in a function from decorator

Gabriel Genellina gagsl-py2 at
Mon Jul 30 08:15:48 CEST 2007

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

> 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  

import functools

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

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