Functions as first class object in Python
In Python, functions are first class object (first class citizen too!). Programming language theorists defined some criteria for first class object of a programming language. A “first class object” is a program entity which can be :
- created at run time
- can be assigned to a variable
- can be passed as function argument
- can be returned from a function
Let’s examine these criteria for Python functions.
1. Creation in run time
Here, we have a recursive function named print_inversely
which will print n
down to 0
. Number of calls of print_inversely
function depends on value of n
. Depending on value of n
it calls itself. Before running the program it cannot decide about its behavior, number of calls etc. At the run time it calls itself recursively depending on the value of n
. In other word, “here we are creating and calling the function at run time”
In Python, functions are object too.
This describes that, print_inversely
function is an instance of function class.
2. Assigning to a variable
Here we are assigning the print_inversely
function to our_first_class_function
variable and calling the function through the variable!
3. Passing functions as argument
print_inversely_by_user_input
function takes a function as argument and calls it by user input. Here, we are passing print_inversely
to print_inversely_by_user_input
as argument.
4. Returning function from function
print_one_or_two
function returns a function depending of value of n. If we pass n=1
then it will return reference of print_one function
otherwise it will return reference of print_two function
. Here, a function returning another function!
Note: When a function takes a function as argument or returns another function then the function is called higher-order function.
This is my brief discussion on python functions as first class object (first class citizen!) :)