Functions Are Objects, Too

Learn how Python leverages functions as callable objects for dynamic execution and event-driven programming.

We'll cover the following...

Overview

There are numerous situations where we’d like to pass around a small object that is simply called to perform an action. In essence, we’d like an object that is a callable function. This is most frequently done in event-driven programming, such as graphical toolkits or asynchronous servers.

In Python, we don’t need to wrap such methods in a class definition because functions are already objects. We can set attributes on functions (though this isn’t a common activity), and we can pass them around to be called at a later date. They even have a few special properties that can be accessed directly.

Example

Here’s yet another contrived example, sometimes used as an interview question:

Press + to interact
def fizz(x: int) -> bool:
return x % 3 == 0
def buzz(x: int) -> bool:
return x % 5 == 0
def name_or_number(number: int, *tests) -> None:
for t in tests:
if t(number):
return t__name__
return str(number)
for i in range(1, 11):
print(name_or_number(i, fizz, buzz))

The fizz() and buzz() functions check to see whether their parameter, x, is an exact multiple of another number. This relies on the definition of the modulo operator: if xx ...