F
Francesco Bochicchio
Hi all,
I found a strange (for me) behaviour of inner function. If I execute
the following code:
# file in_f.py -----------
def dec_f(f):
def inner_f():
if f.enabled:
f()
return inner_f
@dec_f
def funct():
print "Ciao"
funct.enabled = True
funct()
# end of file -----------------
I get the following exception:
File "/Users/fb/Documents/Prove python/in_f.py", line 15, in
<module>
funct()
File "/Users/fb/Documents/Prove python/in_f.py", line 5, in inner_f
if f.enabled:
AttributeError: 'function' object has no attribute 'enabled'
The same happens when I rebind explicitely the function name instead
of using the decorator:
def funct():
print "Ciao"
funct = dec_f(funct)
It looks like the decorator uses an older instance of 'funct', which
does not yet
have the attribute dinamically attached to it. This seem to be
confirmed by the fact that adding the attribute before
rebinding the function name, the problem disappear:
def funct():
print "Ciao"
funct.enabled = False # this fixes the problem
funct = dec_f(funct)
So I have a workaround, but still don't understant why the original
code does not work.
Anyone can point me to an explanation?
Thanks in advance
Ciao
I found a strange (for me) behaviour of inner function. If I execute
the following code:
# file in_f.py -----------
def dec_f(f):
def inner_f():
if f.enabled:
f()
return inner_f
@dec_f
def funct():
print "Ciao"
funct.enabled = True
funct()
# end of file -----------------
I get the following exception:
File "/Users/fb/Documents/Prove python/in_f.py", line 15, in
<module>
funct()
File "/Users/fb/Documents/Prove python/in_f.py", line 5, in inner_f
if f.enabled:
AttributeError: 'function' object has no attribute 'enabled'
The same happens when I rebind explicitely the function name instead
of using the decorator:
def funct():
print "Ciao"
funct = dec_f(funct)
It looks like the decorator uses an older instance of 'funct', which
does not yet
have the attribute dinamically attached to it. This seem to be
confirmed by the fact that adding the attribute before
rebinding the function name, the problem disappear:
def funct():
print "Ciao"
funct.enabled = False # this fixes the problem
funct = dec_f(funct)
So I have a workaround, but still don't understant why the original
code does not work.
Anyone can point me to an explanation?
Thanks in advance
Ciao