Skip to main content

Fast python callback/event system modeled after Qt Signals

Project description

psygnal

License PyPI Conda Python Version CI codecov Documentation Status

Psygnal (pronounced "signal") is a pure python implementation of Qt-style Signals with (optional) signature and type checking, and support for threading.

Note: this library does not require Qt. It just implements a similar pattern of inter-object communication with loose coupling.

Documentation

https://psygnal.readthedocs.io/

Install

pip install psygnal
conda install -c conda-forge psygnal

Usage

A very simple example:

from psygnal import Signal

class MyObject:
    value_changed = Signal(str)
    shutting_down = Signal()

my_obj = MyObject()

@my_obj.value_changed.connect
def on_change(new_value: str):
    print(f"The value changed to {new_value}!")

my_obj.value_changed.emit('hi')

Much more detail available in the documentation!

Evented Dataclasses

A particularly nice usage of the signal pattern is to emit signals whenever a field of a dataclass changes. Psygnal provides an @evented decorator that will emit a signal whenever a field changes. It is compatible with dataclasses from the standard library, as well as attrs, and pydantic:

from psygnal import evented
from dataclasses import dataclass

@evented
@dataclass
class Person:
    name: str
    age: int = 0

person = Person('John', age=30)

# connect callbacks
@person.events.age.connect
def _on_age_change(new_age: str):
    print(f"Age changed to {new_age}")

person.age = 31  # prints: Age changed to 31

See the dataclass documentation for more details.

Benchmark history

https://pyapp-kit.github.io/psygnal/

Developers

Debugging

While psygnal is a pure python module, it is compiled with Cython to increase performance. To import psygnal in uncompiled mode, without deleting the shared library files from the psyngal module, set the environment variable PSYGNAL_UNCOMPILED before importing psygnal. The psygnal._compiled variable will tell you if you're running the compiled library or not.

Supported by

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