From d53d7fecc346c7ce65f5e91f16308198168814e8 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Sat, 20 Sep 2025 23:35:11 +0200 Subject: [PATCH] MNT: Define Protocol for Animation.event_source Also, event_source is a mandatory parameter and cannot be None, because Animation.__init__ calls `event_source.add_callback()`. --- ci/mypy-stubtest-allowlist.txt | 3 +++ lib/matplotlib/animation.py | 4 ++-- lib/matplotlib/animation.pyi | 12 +++++++++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/ci/mypy-stubtest-allowlist.txt b/ci/mypy-stubtest-allowlist.txt index 46ec06e0a9f1..12b6feb9b2e0 100644 --- a/ci/mypy-stubtest-allowlist.txt +++ b/ci/mypy-stubtest-allowlist.txt @@ -49,3 +49,6 @@ matplotlib\.figure\.FigureBase\.get_figure # getitem method only exists for 3.10 deprecation backcompatability matplotlib\.inset\.InsetIndicator\.__getitem__ + +# only defined in stubs; not present at runtime +matplotlib\.animation\.EventSourceProtocol diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index 8756cb0c1439..56fda4ec6849 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -861,7 +861,7 @@ class Animation: fig : `~matplotlib.figure.Figure` The figure object used to get needed events, such as draw or resize. - event_source : object, optional + event_source : object A class that can run a callback when desired events are generated, as well as be stopped and started. @@ -877,7 +877,7 @@ class Animation: FuncAnimation, ArtistAnimation """ - def __init__(self, fig, event_source=None, blit=False): + def __init__(self, fig, event_source, blit=False): self._draw_was_started = False self._fig = fig diff --git a/lib/matplotlib/animation.pyi b/lib/matplotlib/animation.pyi index f725df8ebb22..e90a0103aefd 100644 --- a/lib/matplotlib/animation.pyi +++ b/lib/matplotlib/animation.pyi @@ -6,7 +6,7 @@ from matplotlib.artist import Artist from matplotlib.backend_bases import TimerBase from matplotlib.figure import Figure -from typing import Any +from typing import Any, Protocol subprocess_creation_flags: int @@ -152,11 +152,17 @@ class HTMLWriter(FileMovieWriter): def grab_frame(self, **savefig_kwargs): ... def finish(self) -> None: ... +class EventSourceProtocol(Protocol): + def add_callback(self, func: Callable): ... + def remove_callback(self, func: Callable): ... + def start(self): ... + def stop(self): ... + class Animation: frame_seq: Iterable[Artist] - event_source: Any + event_source: EventSourceProtocol | None # TODO: We should remove None def __init__( - self, fig: Figure, event_source: Any | None = ..., blit: bool = ... + self, fig: Figure, event_source: EventSourceProtocol, blit: bool = ... ) -> None: ... def __del__(self) -> None: ... def save(