- First Class Functions in Python
- Defining functions
- Storing functions in variables
- Passing functions as arguments
- Returning functions
- Advantages of first class functions
- First Class functions in Python
- What are the properties of First Class Functions?
- Example code
- Output
- Example code
- Output
- Example code
- Output
- What are First Class Functions in Python?
- First Class Object
- First Class Functions
- What Next
- Would You Like to Support Me?
First Class Functions in Python
Python supports all these features so functions are treated as first class citizens.
This is not a python only feature by any means, many other languages treat functions as their first class citizens, namely JavaScript, PHP, Perl. They are pretty much a necessity for the functional programming style.
Defining functions
As you must already know we define functions in Python with the def keyword.
The function gets stored at a memory location as shown below at the address 0x0376CB28 .
>>> foo function foo at 0x0376CB28>
Storing functions in variables
As function in python are first class citizens you can store the function in a variable.
>>> foo function foo at 0x0376CB28> >>> bar = foo >>> bar function foo at 0x0376CB28>
Even though the function is assigned to a separate variable bar notice that the location of the function still stays the same. Its merely 2 variables storing the location of the same function in the memory.
Not only you can store them in simple variables but you can store functions in a list, dict and other data structures as shown below.
# storing in list >>> mylist = [] >>> mylist.append(foo) # storing in dict >>> mydict = <> >>> mydict['function_foo']= foo
Passing functions as arguments
Functions can be passed as arguments to another function. Check out the sample below.
def main(func): print(func) def foo(): pass print(foo) main(foo)
function foo at 0x0163CD68> function foo at 0x0163CD68>
The function foo is passed as an argument to the function main and we can confirm that it is the same function foo which main has received as the argument by printing the memory address (feature of CPython) of the function globally as well as within the main function.
Returning functions
Similarly a function can return another function.
def foo(): pass def main(): return foo # returns a function bar = main()
As you see the memory address is still the same for foo and bar .
>>> foo function foo at 0x009CF6F0> >>> bar function foo at 0x009CF6F0>
Advantages of first class functions
There can be numerous benefits of this approach, some of them are listed below. You can check out the below topics to further dig deeper.
First Class functions in Python
In different programming languages, First Class objects are those objects, which can be handled uniformly. First Class objects can be stored as Data Structures, as some parameters of some other functions, as control structures etc. We can say that a function in Python is First Class Function, if it supports all of the properties of a First Class object.
What are the properties of First Class Functions?
- It is an instance of an Object type
- Functions can be stored as variable
- Pass First Class Function as argument of some other functions
- Return Functions from other function
- Store Functions in lists, sets or some other data structures.
At first we will see how Functions in Python can be used as an object. In Python, a function can be assigned as variable. To assign it as variable, the function will not be called. So parentheses ‘()’ will not be there.
Example code
def cube(x): return x*x*x res = cube(5) print(res) my_cube = cube #The my_cube is same as the cube method res = my_cube(5) print(res)
Output
Now we will see how functions can be passed as argument of another functions. Here is the example.
Example code
def cube(x): return x*x*x defmy_map(method, argument_list): result = list() for item in argument_list: result.append(method(item)) return result my_list = my_map(cube, [1, 2, 3, 4, 5, 6, 7, 8]) #Pass the function as argument print(my_list)
Output
[1, 8, 27, 64, 125, 216, 343, 512]
Here is the third property of First Class Functions. In this case we will return one function from another function.
Example code
defcreate_logger(message): deflog(): print('Log Message: ' + message) return log #Return a function my_logger = create_logger('Hello World') my_logger()
Output
Learning faster. Every day.
What are First Class Functions in Python?
You might have heard of the famous saying, «In Python, everything is an object». Very confusing as it may sound, this is absolutely true. In Python, every single entity is represented as an object ( Yes, object from the OOP. In case you don’t know about OOP, I have got it briefly covered in this article ). This concept has given rise to many methodologies and principles in Python like Closures and Decorators.
Psst.. If you are in a hurry, you can watch the video version of this post instead
First Class Object
To keep it short and simple, A first-class object is an entity within a programming language that can:
- Appear in an expression
- Be assigned to a variable
- Be used as an argument
- Be returned by a function call
So, what do you think would be candidates to this? Well, Python datatypes fit these criteria, so datatypes like Integer, String, Boolean etc are first-class objects. So, let me ask: Are loops and conditionals first-class objects? Of course not since they both are failing multiple criteria. Finally, we can achieve all the aforementioned with functions as well! Therefore, functions are also first-class objects.
First Class Functions
In programming languages like Python, JavaScript, we have functions as First-Class Objects. Hence, the formal name of a function is First-Class Function (although we just call it function). First-Class Functions can be treated as any other object. This means that in Python, functions can be passed around, tossed in as arguments to other functions and even be assigned to variables.
Given below is a function which increments a number by 1:
def plusOne(number): return number+1
Now to prove that functions can be treated as other objects, let me go ahead and rename this function like so:
def plusOne(number): return number+1 #renaming the above function re = plusOne #calling both the functions plusOne(10) # 11 re(10) # 11
You’d notice that both of them gives you the same output. Do you remember encountering this behavior elsewhere? Well, if you run the following code, you might get an idea:
x = 11 y = x print(x) # 11 print(y) # 11
Surprising ain’t it? Therefore, functions behave like the first-class objects. This is something unique that other programming languages like C, C++ never had. Functions in Python can be treated as first class objects (String, Integer, etc).
Now, I am going to spice things up. This might seem a bit weird in the beginning but you will understand it and grasp the concept pretty quick.
If you remember that we can store the First Class Objects in some other data structure like Lists, Dictionaries right? Well, this means that a function too can be stored in these data structures and used accordingly. Let me explain this more briefly (using List as the data structure):
def plusOne(number): return number+1 def plusTwo(number): return number+2 def plusThree(number): return number+3 def plusFour(number): return number+4 # list storing function objects func_list = [plusOne, plusTwo, plusThree, plusFour] # executing each function for func in func_list: print(func(10)) # It will print out ---> 11, 12, 13, 14
In the above snippet, I have created a func_list list which will store the function objects. Now, before I move further, it is imperative to understand that Python does not make a call to the function unless you succeed it with brackets () . So, if I only do this:
Python would only give me the function reference as shown above. Alright, let’s go back. Now, the func_list holds the function objects (which are not yet executed). Then, I ran a for loop, accessed each function and then finally executed it with the help of parenthesis and a parameter, 10.
Great stuff! I believe now you got to know what the original behavior of functions are. To truly solidify your grasp on this concept, try to make use of it wherever you find its possible use case.
Let me try and come up with a use case of first class functions:
def plusOne(number): return number+1 def plusTwo(number): return number+2 def listModifier(li, func): result = [] for element in li: result.append(func(element)) return result # executing listModifier print(listModifier([1,2,3,4], plusOne)) # prints out ---> [2,3,4,5]
In the above snippet, I passed a function ( plusOne ) as the parameter to another function ( listModifier ). Then, I made a call to plusOne from within the listModifier function. This would trigger the plusOne function and will increment each value of list passed and then append it to a result list. Finally, after the above operation, simply returned result .
Now, let’s suppose for some reason, the client comes to me and tells me that instead of incrementing each value of the element by 1, do it by 2, all I would have to do is simply replace the plusOne parameter of listModifier to plusTwo like so:
print(listModifier([1,2,3,4], plusTwo)) # pretty neat eh? # prints out ---> [3,4,5,6]
What Next
Let me tell you that, you have reached a major milestone by learning this concept. First Class Function form the basis of several other design patterns and concepts such as Closures and Decorators. You’d have a better understanding of those topics by having a knowledge of first class functions beforehand.
Would You Like to Support Me?
If you want to support me and my contents, then go ahead and consider doing it. I would highly appreciate that: