psygnal

0.15.1 · active · verified Sat Apr 11

Psygnal is a pure Python implementation of the observer pattern, providing a fast callback and event system modeled after Qt Signals & Slots. It offers optional signature and type checking for connected slots and supports threading, all without requiring or using Qt. The current version is 0.15.1, and the library is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a signal, connect multiple callbacks (both directly and with a decorator), emit a signal, and disconnect a callback. Note that a signal is only emitted if the value truly changes.

from psygnal import Signal

class MyObject:
    """A simple object that emits a signal when its value changes."""
    value_changed = Signal(str)

    def __init__(self, initial_value: str = ""):
        self._value = initial_value

    def set_value(self, new_value: str):
        if new_value != self._value:
            self._value = new_value
            self.value_changed.emit(self._value)

# Create an instance of the object
my_obj = MyObject("start")

# Connect a callback function using the .connect() method
def on_value_change_method(new_value: str):
    print(f"Callback 1 (method): The value changed to '{new_value}'!")

my_obj.value_changed.connect(on_value_change_method)

# Connect another callback function using the @.connect decorator
@my_obj.value_changed.connect
def on_value_change_decorator(new_value: str):
    print(f"Callback 2 (decorator): I also received: '{new_value}'!")

print("Initial value set, no emission yet.")

# Emit signals by changing the value
print("\nSetting value to 'hello':")
my_obj.set_value("hello")

print("\nSetting value to 'world':")
my_obj.set_value("world")

print("\nSetting value to 'world' again (should not emit):")
my_obj.set_value("world")

# Disconnect a callback
my_obj.value_changed.disconnect(on_value_change_method)
print("\nDisconnected 'Callback 1'. Setting value to 'psygnal':")
my_obj.set_value("psygnal")

view raw JSON →