This is a closure. In Python functions are first class function. A function inside a function have access to variables which are defined in the outer function. A function can return a function.
def foo():
# local variable in function
# foo
greeting = 'Hello World'
def bar():
# access to local variable
# greeting of
# function foo
print(greeting)
# return the function
# bar
# without calling it
return bar
When you call
foo()
, it returns the function
bar
. Then you can call the returned function, which has still access to the variable
greeting
.
inner_function = foo()
inner_function() => prints Hello World
or
foo()()
The statement
def
is an assignment for a
function
to a
name
.
You can write it with a lambda:
function_name = lambda x: x ** 2
function_name.__name__ = 'function_name'
Written with lambda with your example:
def externa(x):
interna = lambda y: y**x
# the variable x is not in the
# function definition of interna
# it's in the function definition of externa
return interna
# this returns interna
# but does it not call it
I think you should have enough knowledge to understand what happens.
Outer function returns inner function. Inner function has access local variables of outer function.
A function can return a function. You can return a function without calling the function.