Skip to content

Commit

Permalink
fix: automatically unsubscribe autoruns when the weakref is dead
Browse files Browse the repository at this point in the history
  • Loading branch information
sassanh committed Mar 22, 2024
1 parent cbfdc9a commit 291ff97
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Version 0.12.7

- fix: automatically unsubscribe autoruns when the weakref is dead

## Version 0.12.6

- refactor: drop logging fixture and use standard pytest logger in tests
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "python-redux"
version = "0.12.6"
version = "0.12.7"
description = "Redux implementation for Python"
authors = ["Sassan Haradji <[email protected]>"]
license = "Apache-2.0"
Expand Down
6 changes: 4 additions & 2 deletions redux/autorun.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__( # noqa: PLR0913
elif inspect.ismethod(func):
self._func = weakref.WeakMethod(func)
else:
self._func = weakref.ref(func)
self._func = weakref.ref(func, lambda _: self.unsubscribe())
self._options = options

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

store.subscribe(self._check_and_call, keep_ref=options.keep_ref)
self.unsubscribe = store.subscribe(self._check_and_call)

def inform_subscribers(
self: Autorun[
Expand Down Expand Up @@ -175,6 +175,8 @@ def _check_and_call(
)
else:
self.inform_subscribers()
else:
self.unsubscribe()

def __call__(
self: Autorun[
Expand Down
2 changes: 2 additions & 0 deletions tests/test_weakref.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# ruff: noqa: D100, D101, D102, D103, D104, D107
from __future__ import annotations

import gc
import weakref
from dataclasses import replace
from typing import TYPE_CHECKING, Generator
Expand Down Expand Up @@ -115,6 +116,7 @@ def render_without_keep_ref(_: int) -> int:

ref = weakref.ref(render_without_keep_ref)
del render_without_keep_ref
gc.collect()
assert ref() is None

store.dispatch(IncrementAction())
Expand Down

0 comments on commit 291ff97

Please sign in to comment.