decorator and function local variable

Diez B. Roggisch deets at nospam.web.de
Mon Feb 20 19:15:06 EST 2006


Grzegorz Smith schrieb:
> Hi all. I have got situation that I need make parameter injection into
> function and I want that parametet be a local variable of that function.
> eg. something like
> def decorator():
> 	<code>
> @decorator
> def myfun():
>    a = 20
> 
> and in myfun i can use b wariable like that:
> b = "ok it's working"
> I try to use sample decorators from:
> http://www.python.org/moin/PythonDecoratorLibrary 
> but unsuccesfully. Does anyone know hot to achieve this? Or is it possible?

I don't fully understand what you're after here - but are you aware of the __call__-method on objects? You might very 
well do it like this:


class Foo:
   def __init__(self, parameter):
       self.parameter = parameter

   def __call__(self, *args):
       return "%r %r" % (self.parameter, args)

Then you can do

f = Foo()

f(1,2,3,4)

And if you need to alter f's working by means of parameter, just assign it a new value.

Diez



More information about the Python-list mailing list