Re: making a variable available in a function from decorator
- From: "Gabriel Genellina" <gagsl-py2@xxxxxxxxxxxx>
- Date: Mon, 30 Jul 2007 03:15:48 -0300
En Sun, 29 Jul 2007 19:22:47 -0300, rkmr.em@xxxxxxxxx <rkmr.em@xxxxxxxxx> 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
.
- Prev by Date: Re: Compiling 2.5.1 on OpenBSD 4.1
- Next by Date: Re: making a variable available in a function from decorator
- Previous by thread: Re: making a variable available in a function from decorator
- Next by thread: What is the difference about "pycap" and "pylibpcap"?
- Index(es):