Using decorators when calling functions instead of function definitions

Whenever I see a decorator in python, I always see that it uses function definitions

def logger(func):
    def inner(*args, **kwargs): #1
        print "Arguments were: %s, %s" % (args, kwargs)
        return func(*args, **kwargs) #2
    return inner

@logger
def func(x, y=1):
    return x * y

func(2) # Returns Arguments were: (2,), {} \n 2

What would be an equivalent way of doing what the decorator does when defining a function, but allows you to call it when you call the function so that the function can be used with and without a “decorator”?

(Below I hope, and although I do not think that you could do this with a decorator, I use @to show this idea)

def func(x, y=1):
    return x * y

func(2) # returns 2

@logger
func(2)  # Returns Arguments were: (2,), {} \n 2 
+4
source share
1 answer

@logger func logger , func. :

logger(func)(2)

logger(func) , , func. , (2) .

, logger() .

f = logger(func)
f(2)
f(3)
f(4)
+5

Source: https://habr.com/ru/post/1535583/


All Articles