Functional Programming
Function Object
Everything in a Python program is an object, a function is also an object
def func():
print('Hello World!')
f = func
print(id(f), id(func)) # 140232159555440 140232159555440
print(type(f)) # <class 'function'>
print(f) # <function func at 0x7f81700e6f70>
f() # Hello World!
Function Inspect Information
import inspect
# function comment
def func():
"""Function Doc
"""
print('Hello World!')
if __name__ == '__main__':
f = func
print(inspect.isfunction(f)) # check if an object is a function
print(inspect.getdoc(f)) # get the object doc string
print(inspect.getcomments(f)) # get comments before function
print(inspect.getfile(f)) # get the file name in which the function is defined
print(inspect.getsource(f)) # get the source code
Function Composition
To take another function as an argument
The inner function is referred to as a callback, because a call back to the inner function can modify the outer function’s behavior
def inner():
print('Hello World!')
def outer(f):
f()
outer(inner) # Hello World!
def inner(a, b):
return a+b
def outer(f, x, y):
return f(x, y)
print(outer(inner, 1, 2)) # 3
Return Function
To return another function to its caller
def outer():
def inner():
print('Hello World!')
return inner
f = outer()
f() # Hello World!
Anonymous Function
lambda [parameter_list]: [expression], return one single expression
add = lambda a, b: a+b
print(add(1, 2))
print((lambda a, b: a+b)(1, 2))
Reference