Here’s another article in the Functions in Python series. Today we’ll be talking about assigning functions to variables. If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
9) Arbitrary Number of Keyword Parameters
10) Arbitrary Number of Both Positional and Keyword Parameters
11) Nested Functions
12) Calling Functions in Other Functions
Functions are first-class objects, which means they are objects like any other objects, which further means they can be used just like other objects. Translating this into plain English, we can assign functions to variables and pass them as arguments to other functions. They can also be returned from other functions. If you want to read more about functions as first-class objects, I have an article about that.
Now let’s focus on assigning functions to variables. If you assign a function to a variable, you can use the variable as the function:
def double(number):
return number * 2
print(double(5))
a = "abc"
print(a)
a = double
print(a(17))
b = a
print(b(12))
Here’s the output:
10
abc
34
24
So, in the code above the variable a was first assigned a string. Then it was assigned the double function. From this point on it’s possible to use a as the double function. Finally the variable b was assigned the same reference as a, so it also now points to the double function. In the end, we can use double, a or b and they all reference the same function.