Function Objects and Callbacks
Explore how Python's object-oriented and functional programming features intersect by using function objects as callbacks. Understand the design and implementation of a Task class and a Scheduler class to execute tasks at scheduled intervals. Learn how callbacks allow flexible, event-driven programming useful in user interfaces and IoT applications.
We'll cover the following...
The fact that functions are top-level objects is most often used to pass them around to be executed at a later date, for example, when a certain condition has been satisfied. Callbacks are common as part of building a user interface: when the user clicks on something, the framework can call a function so the application code can create a visual response. For very long-running tasks, like file transfers, it is often helpful for the transfer library to call back to the application with status on the number of bytes transferred so far—this makes it possible to display status thermometers to show status.
Example
Let’s build an event-driven timer using callbacks so that things will happen at scheduled intervals. This can be handy for an IoT (Internet of Things) application built on a small CircuitPython or MicroPython device. We’ll break this down into two parts: a task, and a scheduler that executes the function object stored in the task.
The Task class
Here’s the code for Task class:
Code explanation
-
Attributes: The
Taskclass definition has two mandatory fields and two optional fields. The mandatory fields,scheduledandcallback, provide a scheduled time to do something and a callback function, the thing to be done at the scheduled time. The scheduled time has aninttype hint; the time module can use floating-point time, for super-accurate operations. We’re going to ignore these details. Also, the mypy tool is well aware that integers can be coerced to floating-point numbers, so we don’t have to be super-fussy-precise about numeric types. -
...