Search code examples
pythondecorator

Python decorator not executing


I am working on a decorator to register functions easier in my app, so I made a "do twice" decorator to test if i understood decorators correctly. I tried doing it, but it didn't work. Could someone help me?

My code (decorator.py):

def do_twice(func):
    def wrapper_do_twice():
        func()
        func()
    return wrapper_do_twice

My code (main.py):

from decorator import do_twice


@do_twice
def say_whee():
    print("Whee!")

I expected the function to say_whee() to be executed twice and give the output

Whee! 
Whee!

But there was no output.


Solution

  • If that is your full main.py you never called the function say_whee(). You should call it afterwards either directly or in a if __name__ == '__main__' block:

    from decorator import do_twice
    
    
    @do_twice
    def say_whee():
        print("Whee!")
    
    say_whee()
    

    or

    from decorator import do_twice
    
    
    @do_twice
    def say_whee():
        print("Whee!")
    
    if __name__ == "__main__":
        say_whee()