First Class Functions in Python
First class functions are used for declaring functions within functions, as well as passing functions as arguments. Functions that contain the declared or passed functions are called high order functions. Functions within another function are called low order functions.
def high_order_function(passed_params, lower_function): #call passed in function lower_function(passed_params) #declare another function within the higher order function def another_lower_function(passed_params): #code to execute for this function return some_value #lower order functions can be used as return statements return another_lower_function
Lower order functions have access to variables initialized in the high order function.
Lower order functions often use tuples and dictionaries as parameters.
#first class function def compare(operator, a, b): return operator(a, b) #lower order functions def min(a, b): return a if a < b else b def max(a, b): return a if a > b else b def equals(a, b): return true if a == b else false #calling first class function result = compare(max, 5, 10)