Skip to main content

C#-style event handling mechanism for Python

Reason this release was yanked:

one of the added features has a critical bug (fixed in 0.2.1)

Project description

C#-Style Event Handling Mechanism for Python

pypi status python license
build issues pull requests

C# provides a very simple syntax using the observer pattern for its event handling system. The aim of this project is to implement the pattern in python as similarly as possible.

In C#, an "event" is a field or a property of the delegate type EventHandler. Since delegates in C# can be combined and removed with += and -= operators, event handlers can easily subscribe to or unsubscribe from the event using those operators.

Python does not support an addition of two Callable types. So the Event[P] class is provided to mimic delegates:

from cs_events import Event

on_change = Event[object, str]()

Handlers can subscribe to and unsubscribe from the event with the same syntax:

def event_handler(o: object, s: str) -> None: ...

on_change += event_handler
on_change -= event_handler

An event can be raised by simply invoking it with the arguments:

on_change(obj, "value")

Since Event acts just like a delegate from C#, it is not required to be bound to a class or an instance object. This is the major difference to other packages that try to implement the C#-style event system, which usually revolve around a container object for events.

An example class with event fields may look like this:

class EventExample:
    def __init__(self) -> None:
        self.on_update: Event[str] = Event()
        self.__value: str = ""

    def update(self, value: str) -> None:
        if self.__value != value:
            self.__value = value
            self.on_update(value)

obj = EventExample()
obj.on_update += lambda value: print(f"obj.{value=}")
obj.update("new value")

A class decorator @events is provided as a shortcut for event fields:

from cs_events import Event, events

@events
class EventFieldsExample:
    item_added: Event[object]
    item_removed: Event[object]
    item_updated: Event[object, str]

C# also provides event properties with add and remove accessors:

public event EventHandler<T> Changed
{
    add => ...
    remove => ...
}

This feature is useful for classes that do not actually own the events, but need to forward the subscriptions to the underlying object that do own the events.

The @event[P] decorator and the accessors[P] type are provided to support this feature:

from cs_events import accessors, event, EventHandler

class EventPropertyExample:
    @event[str, object]
    def on_change() -> accessors[str, object]:
        def add(self: Self, value: EventHandler[str, object]) -> None:
            ...
        def remove(self: Self, value: EventHandler[str, object]) -> None:
            ...
        return add, remove

Furthermore, the EventHandlerCollection interface is provided to support the functionalities of System.ComponentModel.EventHandlerList class from C#, along with the two implementations EventHandlerList and EventHandlerDict using a linked list and a dictionary respectively. The behaviour of EventHandlerList is exactly the same as of its counterpart from C#.

A typical usage of EventHandlerList in C# can be translated directly into the python code:

class EventPropertyExample:
    __event_change: Final = object()

    @event  # [str, object] is inferred
    def on_change():  # -> accessors[str, object] is inferred
        def add(self: Self, value: EventHandler[str, object]) -> None:
            self.__events.add_handler(self.__event_change, value)
        def remove(self: Self, value: EventHandler[str, object]) -> None:
            self.__events.remove_handler(self.__event_change, value)
        return add, remove
    
    def __init__(self) -> None:
        self.__events = EventHandlerList()
    
    def perform_change(key: str, value: object) -> None:
        e = self.__events[self.__event_change]
        if e is not None:
            e(key, value)

The class decorator @events also provides a shortcut for event properties. The above code can be shortened to:

@events(collection="__events", prefix="on_")
class EventPropertyExample:
    on_change: event[object, str]

    def __init__(self) -> None:
        self.__events = EventHandlerList()

    def perform_change(key: str, value: object) -> None:
        self.__events.invoke("change", key, value)

Installation

Install using pip:

pip install cs-events

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cs-events-0.2.0.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cs_events-0.2.0-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file cs-events-0.2.0.tar.gz.

File metadata

  • Download URL: cs-events-0.2.0.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.2

File hashes

Hashes for cs-events-0.2.0.tar.gz
Algorithm Hash digest
SHA256 9e711e6c7356d62be8f1f6bd299f9d6f6af73350fe5578669b7a13161324012e
MD5 4827985b3c988cb287d68e68300f76b8
BLAKE2b-256 0ee035c1b8697b5be46d05baebcc6cfeda35e36835dfa74d6659335895272e40

See more details on using hashes here.

File details

Details for the file cs_events-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: cs_events-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 9.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.2

File hashes

Hashes for cs_events-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8f6bf50f868c3e5cc77eede09c34673b88629e704d9819de8b687d270ebdec42
MD5 ad00ed00562ca5ab0cbebcef7ba6b7ec
BLAKE2b-256 41cbbf30ab85f67a9c81f510bfddc06dbf0c1799848672f835631034fa128fb9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page