Skip to content

feat: make Signal and SignalInstance generic - #446

Draft
jacopoabramo wants to merge 6 commits into
pyapp-kit:mainfrom
jacopoabramo:feat/generic-signals
Draft

jacopoabramo wants to merge 6 commits into
pyapp-kit:mainfrom
jacopoabramo:feat/generic-signals

Conversation

@jacopoabramo

@jacopoabramo jacopoabramo commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Assisted by Opus 5.5 (code is generated by it and reviewed by me, PR text is my own)

Supersedes #304

This PR makes Signal and SignalInstance generic over the types they emit, so Signal(int) gives SignalInstance[int] on instances, and type checkers now check connect, emit, emit_fast and __call__ against those types.

Signal(...) supports construction with up to 5 types, unions included.

Apparently, the problem is in Python's typing system, and we can't support any number of types. i.e.

Ts = TypeVarTuple("Ts")

class Signal(Generic[Unpack[Ts]]):
    def __init__(self, *types: Unpack[Ts]) -> None: ...

Signal(int, str)   # arguments have types type[int], type[str]
                   # Ts = (type[int], type[str])
                   # result: Signal[type[int], type[str]]   <- not Signal[int, str]

The approach suggested in PEP 646 is one overload per number of types. #304 did this for connect; here the constructor does it too, so that the parameters are the emitted types rather than type[...]. The limit of 5 is the MAX_ARGS #304 already used. The _connector.pyi stub holds the annotations the overloads share.

Right now it focuses only on Signal and SignalInstance. I deferred typing the rest of the API (SignalGroup, evented containers, etc.) to a later PR.

While reviewing this work I realized why I started #445 first: a generic class needs TypeVarTuple and Unpack at runtime, typing has them only from 3.11, and psygnal has no runtime dependencies.

This PR keeps 3.10 and adds no dependency: on 3.10 the two names come from typing_extensions when it is installed. Without it, on 3.10 only, the classes accept a single type argument at runtime (SignalInstance[int, str] raises TypeError); static checking is not affected.

That fallback lives in a new _typing.py module, excluded from the mypyc build because mypyc cannot run an else branch after if TYPE_CHECKING (mypyc/mypyc#1159). Requiring Python 3.11 would remove the module and the limitation, so up to you.

At this time the PR cannot be merged, because the mypyc build needs python/mypy#22169, which is not in a release yet. So we still have to wait on that before making a decision. Locally, with mypyc cloned from main the build works.

You'll notice that the overloads of Signal.__init__ and SignalInstance.connect take their keyword arguments as typed dictionaries (**kwargs: Unpack[...]).

The intention was to keep the overloads readable, because otherwise every overload repeats the full keyword list, which is a huge amount of text. I'm not particularly happy with it, so feel free to offer an alternative (I'm guessing right now the only alternative is to keep the overloads as they are and drop the typed dictionaries... wordy but it'll be the truth about the types).

My concern is: is there anybody who's using more than 5 types to declare signals? Of that I have no clue.

The first commit is unrelated: it makes the typing CI job install pytest-mypy-plugins on Python 3.14, where it was being skipped.

@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.68%. Comparing base (b5f2ea1) to head (5cd34a4).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #446      +/-   ##
==========================================
- Coverage   99.68%   99.68%   -0.01%     
==========================================
  Files          23       23              
  Lines        2559     2522      -37     
==========================================
- Hits         2551     2514      -37     
  Misses          8        8              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jacopoabramo

Copy link
Copy Markdown
Contributor Author

I pinged mypy to ask when a new release is expected with the required fix. They're pushing for more frequent releases in the last few months so maybe we're lucky...

@jacopoabramo

Copy link
Copy Markdown
Contributor Author

Pushed two commits fixing a regression this branch introduced: connect on an untyped signal no longer returned the slot's own type (pyright gave Any, mypy gave def (*Any, **Any) -> Any when the slot mentioned Any).

5d6f391 types untyped signals as SignalInstance[Never] instead of SignalInstance[*tuple[Any, ...]], so the checkers can tell them from typed ones:

  • connect on an untyped signal returns the slot unchanged, as on main
  • emit, emit_fast and __call__ on an untyped signal accept any arguments
  • this covers Signal(Signature()), more than five types, a SignalInstance built directly, and signals reached through a SignalGroup
  • restores the two expectations in typesafety/test_signal.yml that I had adjusted to match the regression
  • annotations only, no runtime change

5cd34a4 rewrites the new checks in typesafety/signal_types.py with one call per line, so a line expected to fail can only fail on the call it is about.

Remaining difference from main: mypy still erases a slot that mentions Any and takes one positional argument. Never is a placeholder; a private marker class would close that case and read better in hovers, if you prefer it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant