Skip to content

Commit

Permalink
Allow early return from effects (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshKarpel authored Feb 28, 2024
1 parent 0ebfdaf commit 744e23b
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
7 changes: 7 additions & 0 deletions counterweight/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,14 @@ async def forever() -> None:

async def cancel(task: Task[T]) -> None:
# Based on https://discuss.python.org/t/asyncio-cancel-a-cancellation-utility-as-a-coroutine-this-time-with-feeling/26304/2
if task.done():
# If the task has already completed, there's nothing to cancel.
# This can happen if, for example, an effect aborts itself by returning,
# and then we try to cancel it when reconciling effects.
return

task.cancel()

try:
await task
except CancelledError:
Expand Down
14 changes: 14 additions & 0 deletions docs/reference/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,22 @@

## Next

## `0.0.9`

Released `2024-02-27`

### Fixed

- [#121](https://github.com/JoshKarpel/counterweight/pull/121)
A change in effect reconciliation introduced in `0.0.8` caused a regression in the behavior of `use_effect`,
where if the `setup` function `return`ed (i.e., stopped itself),
Counterweight would crash when trying to cancel the effect.
This now works again.

## `0.0.8`

Released `2024-02-17`

### Changed

- [#110](https://github.com/JoshKarpel/counterweight/pull/110)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "counterweight"
version = "0.0.8"
version = "0.0.9"
description = "An experimental TUI framework for Python, inspired by React and Tailwind"
readme="README.md"
homepage="https://github.com/JoshKarpel/counterweight"
Expand Down
11 changes: 11 additions & 0 deletions tests/utils/test_cancel.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,14 @@ async def t() -> None:

with pytest.raises(RuntimeError):
await cancel(task)


async def test_cancel_with_task_that_has_already_finished() -> None:
async def t() -> None:
return

task = create_task(t())

await task # run the task to completion

await cancel(task)

0 comments on commit 744e23b

Please sign in to comment.