It has some possible uses. The main ones are these two:
function factory
That might be the main use. Since functions are first-class objects in Python, each time a function containing others is called, the functions declared internally are recreated (But not compiled again: the bytecode of the nested functions is created in an earlier step). They will have access to the external function variables, which will also be separated from each call (which creates a "closure").
I think one of the most common uses is when writing a Python decorator. Python decorators are functions that receive as a single parameter another function. They return a calling object, usually a function as well, which can execute some code before and after the call of the original function. So a simple decorator’s code goes like this:
def decorator(func):
def wrapper(*args, **kwargs):
# código anterior a chamada original
...
result = func(*args, **kwargs)
# código posterior a chamada original
...
return result
return wrapper
@decorator
def minha_funcao():
...
In this case, each time "my_function" is called, what will be executed will be the function wrapper
sloped within the decorator
- but a function wrapper
where the variable func
will be exactly the function parameter decorator
who receives minha_funcao
original as parameter.
If the decorator is used more than once, func
will receive the other decorated functions, and a function will be created wrapper
distinct for each use.
It is interesting to keep in mind that a nested function can access the variables of the external functions, and, in Python 3, even assign new values to these variables , using the declaration nonlocal
(in Python 2, the external variables were read-only).
readability
Python deliberately restricts the functions of the "lambda" type to being just an expression. In general, "lambda" functions are used as parameters for other functions, for example to obtain the sorting key of a sequence in the method sort
, or a command to be executed when a graphical program button is clicked.
If the function to be passed as parameter is a little more complex, and needs to have variables, if
s, etc... already worth declaring it as an independent function, nested.
Nothing would prevent this nested function from being outside the main code - but the nested statement allows it to be near the point where it is used only once - and if that logic is related to the outside function.