I have the following code:
collector_1 = {}
"""
The usage of spam() decorator is to append a function's name
(the function being decorated by the spam() decorator) as a key
and the function itself (unexecuted) as the value to collector_1.
"""
def spam(collector):
def decorator(function):
collector.update({function.__name__: function})
def wrapper():
print("Wrapper is called.")
return function()
return wrapper
return decorator
@spam(collector_1)
def egg():
print("spam & egg is good.")
I then ran the egg function with this single line of code: egg(); and this is the result that I expected:
The wrapper is called.
spam & egg is good.
But when I ran it using the collector_1 dictionary:
collector_1["egg"]()
It only printed out one message:
spam & egg is good.
My task here is to call the function egg using the collector_1 dictionary, so I can import the collector_1 dictionary from different files to use it; is there any way to resolve this? Any help would be greatly appreciated!
>Solution :
You’re putting the original function in your collector, not the decorated version, which would be wrapper inside your spam function.
Try this instead:
def spam(collector):
def decorator(function):
def wrapper():
print("Wrapper is called.")
return function()
collector[function.__name__] = wrapper
return wrapper
return decorator