Registering Callback Handler Objects
In the examples thus far, C has been running and calling Python code from a standard main program flow of control. That’s not always the way programs work, though; in some cases, programs are modeled on an event-driven architecture in which code is executed only in response to some sort of event. The event might be an end user clicking a button in a GUI, the operating system delivering a signal, or simply software running an action associated with an entry in a table.
In any event (pun accidental), program code in such an architecture is typically structured as callback handlers—chunks of code dispatched by event-processing logic. It’s easy to use embedded Python code to implement callback handlers in such a system; in fact, the event-processing layer can simply use the embedded-call API tools we saw earlier in this chapter to run Python handlers.
The only new trick in this model is how to make the C layer know what code should be run for each event. Handlers must somehow be registered to C to associate them with future events. In general, there is a wide variety of ways to achieve this code/event association; for instance, C programs can:
Fetch and call functions by event name from one or more module files
Fetch and run code strings associated with event names in a database
Extract and run code associated with event tags in HTML or XML[*]
Run Python code that calls back to C to tell it what should be run
And so on. Really, any place you can associate ...
Get Programming Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.