It is common for larger applications to have modules that publishes and subscribes to events. This post will outline a couple ways to achieve this using [decorators](/blog/pydecorators/) and standard methods.
First let us concern ourselves with a single event since that's the easiest. Here we will create an application class that stores callbacks of functions through the subscribe decorator. Calling `emit` will send a message to all the functions stored in `self.callbacks`.
Let's say you want the application to handle different types of events. Now `self.callbacks` is a dictionary of lists, where the key is the event and the list is the same as the last section. There's an additional layered function on top of `subscribe` this time in order to handle passing an argument into the decorator.
The above approaches assume that the callbacks would be needed for the lifetime of the program. An altnerative is to use the [Observer design pattern](https://en.wikipedia.org/wiki/Observer_pattern).
This assumes that we have two classes, `Observable` and `Observer`. The latter class implements the `notify` method and when it is constructed, it adds itself to the collection contained in the `Observable` class.
[Martin](https://martinheinz.dev/blog/112) wrote a great blog post on how you can use Python weak references so that when your `Observer` class goes out of scope, a copy isn't stored in the `Observable` class and instead gets safely removed from the collection.