En Sun, 29 Jul 2007 19:22:47 -0300, [EMAIL PROTECTED] <[EMAIL PROTECTED]>  
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

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to