making a variable available in a function from decorator

Bruno Desthuilliers bdesth.quelquechose at
Wed Jul 25 21:40:37 CEST 2007

Evan Klitzke a écrit :
> On 7/30/07, rkmr.em at <rkmr.em at> wrote:
>>is it possible to do this without passing it as a function argument?
> Sort of. Functions are objects in python, so you can set attribute on them. E.g.
> def foo():
>     return foo.c
> foo.c = 1
> print foo()

 >>> def foo():
...     print foo.c
 >>> foo.c = 1
 >>> bar = foo
 >>> del foo
 >>> bar()
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 2, in foo
NameError: global name 'foo' is not defined

> Which will print 1. Of course, it would generally be better to write
> your own class for this sort of thing, so that you can set the
> variable in the instance scope.

Indeed. But even with OO, explicit is better than implicit.

More information about the Python-list mailing list