Function Objects and Callbacks

Learn about the function objects and callbacks and their usage with the help of coding examples.

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.


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:

Get hands-on with 1200+ tech skills courses.