Function Decorators in Python

Poseidon Broger :

I am a beginner in python and I am trying to wrap my head around function decorators in python. And I cannot figure out how functions return functions.

I mean in what order does interpreter interprets this function:

def decorator(another_func):
    def wrapper():
        print('before actual function')
        return another_func()
    print('pos')
    return wrapper

And what is the difference between these 2 statements:-

return wrapper

AND

return wrapper()

I am using Head First Python, but this topic I feel is not described very well in there, please suggest any video or a good resource so that I can understand it.

bruno desthuilliers :

I cannot figure out how functions return functions.

As already explained by LTheriault, in python everything is an object. Not only this, but also everything happens at runtime - the def statement is an executable statement, which creates a function object from the code within the def block and bind this object to the function's name in the current namespace - IOW it's mostly syntactic sugar for some operations you could code manually (a very welcome syntactic sugar though - building a function object "by hand" is quite a lot of work).

Note that having functions as "first-class citizens" is not Python specific - that's the basis of functional programming.

I mean in what order does interpreter interprets this function:

def decorator(another_func):
    def wrapper():
        print('before actual function')
        return another_func()
    print('pos')
    return wrapper

Assuming the decorator function is declared at the module top-level: the runtime first takes the code block that follows the def statement, compiles it into a code object, creates a function object (instance of type 'function') from this code object and a couple other things (the arguments list etc), and finally binds this function object to the declared name (nb: 'binds' => "assigns to").

The inner def statement is actually only executed when the outer function is called, and it's executed anew each time the outer function is called - IOW, each call to decorator returns a new function instance.

The above explanation is of course quite simplified (hence partially inexact), but it's enough to understand the basic principle.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=383344&siteId=1