Skip to content

Commit 291ff97

Browse files
committed
fix: automatically unsubscribe autoruns when the weakref is dead
1 parent cbfdc9a commit 291ff97

File tree

4 files changed

+11
-3
lines changed

4 files changed

+11
-3
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## Version 0.12.7
4+
5+
- fix: automatically unsubscribe autoruns when the weakref is dead
6+
37
## Version 0.12.6
48

59
- refactor: drop logging fixture and use standard pytest logger in tests

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "python-redux"
3-
version = "0.12.6"
3+
version = "0.12.7"
44
description = "Redux implementation for Python"
55
authors = ["Sassan Haradji <sassanh@gmail.com>"]
66
license = "Apache-2.0"

redux/autorun.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def __init__( # noqa: PLR0913
5151
elif inspect.ismethod(func):
5252
self._func = weakref.WeakMethod(func)
5353
else:
54-
self._func = weakref.ref(func)
54+
self._func = weakref.ref(func, lambda _: self.unsubscribe())
5555
self._options = options
5656

5757
self._last_selector_result: SelectorOutput | None = None
@@ -68,7 +68,7 @@ def __init__( # noqa: PLR0913
6868
if self._options.initial_run and store._state is not None: # noqa: SLF001
6969
self._check_and_call(store._state) # noqa: SLF001
7070

71-
store.subscribe(self._check_and_call, keep_ref=options.keep_ref)
71+
self.unsubscribe = store.subscribe(self._check_and_call)
7272

7373
def inform_subscribers(
7474
self: Autorun[
@@ -175,6 +175,8 @@ def _check_and_call(
175175
)
176176
else:
177177
self.inform_subscribers()
178+
else:
179+
self.unsubscribe()
178180

179181
def __call__(
180182
self: Autorun[

tests/test_weakref.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# ruff: noqa: D100, D101, D102, D103, D104, D107
22
from __future__ import annotations
33

4+
import gc
45
import weakref
56
from dataclasses import replace
67
from typing import TYPE_CHECKING, Generator
@@ -115,6 +116,7 @@ def render_without_keep_ref(_: int) -> int:
115116

116117
ref = weakref.ref(render_without_keep_ref)
117118
del render_without_keep_ref
119+
gc.collect()
118120
assert ref() is None
119121

120122
store.dispatch(IncrementAction())

0 commit comments

Comments
 (0)