I'm trying to figure out how decorator works in python. But, there are two things that I can't make clear, so I appreciate it if anyone helps me understand how decorator works in python!
This is the sample code I've just written 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")
....:
OUTPUT 1
In [24]: test()
start
hello world
end
The first thing I don't understand is why it outputs "start","hello world","end" when I call test(). I learned that when I call test(), it calls "deco(test)" internally. If so, it should return a "wrapper" function object instead of outputting strings. But, it outputs strings as the result. I'm wondering how it's doing the job 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
I called "deco(test)" just to see what it outputs as the result. As it's shown above, it returns "wrapper" function object and after I assign it to a variable and call "wrapper" function, it outputs two "start"s and one "hello world" and two "end"s. What is going on internally? Why "start" and "end" are outputted twice respectively?
Could anyone please help me understand how this is working?