
Python nested function and decorator - How to use a function that returns another function object
A Python function can return the function.
def f():
def g():
print('g() is called.')
return g()
f()
# g() is called.
f()
returns g()
so g() is called.
is printed.
Return the function object
def f():
def g():
print('g() is called.')
return g
f()
Nothing is printed, that is g()
is not called. For, g
is a function object and f()
simply returns it. In fact, f()
returns the function object g
.
def f():
def g():
print('g() is called.')
return g
a = f()
print(a) # <function f.<locals>.g at 0x103d53e50>
print(type(a)) # <class 'function'>
a
is a function so a()
prints g() is called.
.
def f():
def g():
print('g() is called.')
return g
a = f()
print(a) # <function f.<locals>.g at 0x103d53e50>
print(type(a)) # <class 'function'>
a()
# g() is called.
The argument can be a function object
def f(other_function):
def g():
print('g() is called.')
other_function()
return g
def agree():
print('I agree.')
a = f(agree)
a()
# g() is called.
# I agree.
a
is after all g
so g() is called.
is printed first.
Python decorator
In the above code, a = f(agree)
and a()
seems redundant so Python creates the "decorator".
def f(other_function):
def g():
print('g() is called.')
other_function()
return g
@f
def agree():
print('I agree.')
agree()
# g() is called.
# I agree.
Comments
Powered by Markdown