Passing a class variable as an argument for a decorator function leads to a NameError
for the class name. Running this:
def log(prefix=None):
def decorator(function):
"""Decorates the function"""
def wrapper(*args, **params):
"""Wraps the function"""
name = "-".join([prefix, function.__name__])
result = function(*args, **params)
print(f"completed the execution of '{name}'")
return result
return wrapper
return decorator
class ExampleClass:
_CONSTANT = "test"
def __init__(self, x):
self._x = x
@log(prefix=ExampleClass._CONSTANT)
def product_of_number(self, y):
return self._x * y
if __name__ == "__main__":
x = ExampleClass(3)
x.product_of_number(4)
leads to the error
Traceback (most recent call last):
File "/home/developer/reproduce_decorator_name_space.py", line 23, in <module>
class ExampleClass:
File "/home/developer/reproduce_decorator_name_space.py", line 31, in ExampleClass
@log(prefix=ExampleClass._CONSTANT)
NameError: name 'ExampleClass' is not defined
However, running this
def log(prefix=None):
def decorator(function):
"""Decorates the function"""
def wrapper(*args, **params):
"""Wraps the function"""
name = "-".join([prefix, function.__name__])
result = function(*args, **params)
print(f"completed the execution of '{name}'")
return result
return wrapper
return decorator
_CONSTANT = "test"
class ExampleClass:
def __init__(self, x):
self._x = x
@log(prefix=_CONSTANT)
def product_of_number(self, y):
return self._x * y
if __name__ == "__main__":
x = ExampleClass(3)
x.product_of_number(4)
gives output
completed the execution of 'test-product_of_number'
Why is ExampleClass
not recognized? Decorated method is within class after __init__
and references self. Error message itself refers to module ExampleClass
. How does the class name not exist in name space?