Python Decorator runs on load / import

I am trying to wrap my head around a python decorator. But I don’t understand something. This is my code, my question is related to func_decorate2(decorator with parameter).

def func_decorate(f):
  def wrapper():
    print('wrapped');
    f() 
  return wrapper

@func_decorate
def myfunc1():
  print('func1')

def func_decorate2(tag_name):
  def _(f):
    print('underscore')
    return f
  return _

@func_decorate2('p')
def myfunc2():
  print('func2')

print('call func1')
myfunc1()
print('call func2')
myfunc2()

It will display:

underscore
call func1
wrapped
func1
call func2
func2

Why in this example do I have underscore?

thanks

+4
source share
2 answers

Because it func_decorate2('p')executes immediately and returns the decorator, which itself is immediately executed when the interpreter uses it to decorate myfunc2.

The trick to implement is the part following @- it's just an expression. It does not have to be the function itself - it just needs to evaluate one thing, and the evaluation takes place immediately by definition.

+3

func_decorate2 . , def

def func_decorate2(tag_name):
  def _(f):
    def _fun():
        print('underscore')
        return f
    return _fun
  return _
0

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


All Articles