Functional Programming
Function Object
  • Everything in a Python program is an object, a function is also an object
    1. def func():
    2. print('Hello World!')
    3.  
    4. f = func
    5.  
    6. print(id(f), id(func)) # 140232159555440 140232159555440
    7. print(type(f)) # <class 'function'>
    8. print(f) # <function func at 0x7f81700e6f70>
    9. f() # Hello World!
    10.  
    Function Inspect Information
    1. import inspect
    2.  
    3. # function comment
    4. def func():
    5. """Function Doc
    6. """
    7. print('Hello World!')
    8.  
    9. if __name__ == '__main__':
    10. f = func
    11.  
    12. print(inspect.isfunction(f)) # check if an object is a function
    13. print(inspect.getdoc(f)) # get the object doc string
    14. print(inspect.getcomments(f)) # get comments before function
    15.  
    16. print(inspect.getfile(f)) # get the file name in which the function is defined
    17. 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
    1. def inner():
    2. print('Hello World!')
    3.  
    4. def outer(f):
    5. f()
    6.  
    7. outer(inner) # Hello World!
    1. def inner(a, b):
    2. return a+b
    3.  
    4. def outer(f, x, y):
    5. return f(x, y)
    6.  
    7. print(outer(inner, 1, 2)) # 3
    Return Function
  • To return another function to its caller
    1. def outer():
    2. def inner():
    3. print('Hello World!')
    4.  
    5. return inner
    6.  
    7. f = outer()
    8. f() # Hello World!
    Anonymous Function
  • lambda [parameter_list]: [expression], return one single expression
    1. add = lambda a, b: a+b
    2.  
    3. print(add(1, 2))
    4.  
    5. print((lambda a, b: a+b)(1, 2))
    Reference
  • Functional Programming in Python: When and How to Use It