When I:
Use a classmethod as a decorator wrapper
Have a conditional statement inside the decorator
Put a variable assignment inside the decorator
python raises an UnboundLocalError exception.
However, when I remove the variable assignment and replace it with a print function everything works fine (it does print). Which indicate that the variable is indeed defined.
Snippet 1
class TestClass:
@classmethod
def include(cls, name=None):
def dec(func):
if name is None:
name=1
return func
return dec
@TestClass.include()
def test(): pass
Snippet 2
class TestClass:
@classmethod
def include(cls, name=None):
def dec(func):
if name is None:
print(name)
return func
return dec
@TestClass.include()
def test(): pass
In snippet 1 nothing should happen but it raised the following exception:
Traceback (most recent call last):
File "main.py", line 9, in <module>
@TestClass.include()
File "main.py", line 5, in dec
if name is None:
UnboundLocalError: local variable 'name' referenced before assignment
Snippet 2 prints None as it should.
Am I doing something wrong? or is this a problem in python's implementation?