In Python functions are objects, just like numbers or texts: they can be stored in variables, passed as arguments and returned from other functions.
Storing a function in a variable
def greet(name):
return f"Hello, {name}"
other_name = greet # no parentheses: it is not called, the function is stored
print(other_name("Ana")) # Hello, Ana
print(other_name is greet) # True
greet is the function; greet("Ana") is the result of calling it. That difference is the key to this whole topic.
Passing a function as an argument
A function that receives another function is called a higher-order function. You have already used several: sorted(key=...), map, filter.
def apply_twice(function, value):
return function(function(value))
def double(x):
return x * 2
print(apply_twice(double, 5)) # 20
print(apply_twice(lambda x: x + 3, 5)) # 11
Returning a function
A function can create and return another one. The inner function "remembers" the variables of the function that created it, even though that one has already finished. This is called a closure:
def create_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(10)) # 20
print(triple(10)) # 30
double and triple are different functions, each with its own stored factor. Practice with Multiplier factory.
Closures that change their state: nonlocal
An inner function can read the variables of the outer one, but to modify them it needs to declare them with nonlocal:
def create_counter():
count = 0
def next_value():
nonlocal count
count += 1
return count
return next_value
a = create_counter()
b = create_counter()
print(a(), a(), a()) # 1 2 3
print(b()) # 1
Without the nonlocal count line, Python would raise an UnboundLocalError, because count += 1 would try to create a new local variable. Each counter has its own count, so they do not get mixed up. Practice with Independent counters.
nonlocal versus global
| Keyword | Which variable it modifies |
|---|---|
global | A variable of the main program |
nonlocal | A variable of the nearest outer function |
Whenever you can, avoid both and pass the data as arguments or return it with return. Closures are a handy exception when you want to keep a small, private state.