Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem of calling a decorated function in a dictionary

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"]()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading