How does a decorator work?

I am trying to understand how decorator works in python. But there are two things that I cannot clarify, so I appreciate it if someone helps me understand how the decorator works in python!

This is an example of the code I just wrote to see how it works.

In [22]: def deco(f):
   ....:     def wrapper():
   ....:         print("start")
   ....:         f()
   ....:         print("end")
   ....:     return wrapper

In [23]: @deco
   ....: def test():
   ....:     print("hello world")
   ....:     

EXIT 1

In [24]: test()
start
hello world
end

The first thing I don’t understand is why it returns "start", "hello world", "end" when I call test (). I found out that when I call test (), it calls "deco (test)" internally. If so, it should return a wrapper function object instead of outputting strings. But as a result, it prints the lines. I wonder how this is done internally.

OUTPUT 2

In [28]: i = deco(test)

In [29]: i
Out[29]: <function __main__.wrapper>

In [30]: i()
start
start
hello world
end
end

"deco (test)", , . , "wrapper", , "", "" " " "". ? "start" "end" ?

- , ?

+4
1

, test(), "deco (test)" . , "" . . , .

, - ( , ).

def test():
    print("Hello, world!")
test = deco(test) # note that test is overwritten by the wrapper that deco returns

,

>>> def deco(f):
...     print 'applying deco' # this will print when deco is applied to test
...     def wrapper():
...             print("start")
...             f()
...             print("end")
...     return wrapper
...
>>> @deco
... def test():
...     print("Hello world!")
...
applying deco

, , . " ".

, .

+4

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


All Articles