简体   繁体   中英

Understanding decorator behaviour

I want to understand the decorator behaviour in this code

abc.py

def my_decorator_module(some_function):
    def wrapper():
        num = 10
        if num == 10:
            print('yess')
        else:
            print('no')

        some_function()

        print('print after some_function() called')

    return wrapper()

and call this function as decorator

x.py

from abc import my_decorator_module

@my_decorator_module
def just_some_function():
    print("Wheee!")

output is

yess
Wheee!
print after some_function() called

event I did not call just_some_function() in x.py file when I execute the x.py file return me output, why?

Because you've called wrapper before returning it from your outer decoration function. Don't do that.

return wrapper   # not wrapper()

The tutorial you're following had earlier introduced the concept of returning functions rather than calling them and returning their results; that's what you need to be doing here.

You did not explicitely called just_some_function() but your "decorator" does, cf the last line:

def my_decorator_module(some_function):
    def wrapper():
        num = 10
        if num == 10:
            print('yess')
        else:
            print('no')

        some_function()

        print('print after some_function() called')

    # here !!!   
    return wrapper()

This is actually a faulty implementation - your decorator should not return the result of calling wrapper , but return the wrapper function itself:

    return wrapper

If you don't understand why: the @decorator syntax is only syntaxic sugar so this:

@decorator
def somefunc():
    print("somefunc")

is actually only a shortcut for this:

def somefunc():
    print("somefunc")

somefunc = decorator(somefunc)

so your decorator has to return a function object (or any callable FWIW), usually - but not necessarily - some wrapper that will take care of calling the decorated function (and preferably returning the result).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM