Skip to content

Commit f32fcd8

Browse files
committed
Fixed AssertionError when using nest_asyncio
This stems from the incorrect placement of `nest_asyncio.apply()`, as it should be called before `asyncio.run()`. Fixes #840.
1 parent 1ebfbca commit f32fcd8

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

docs/versionhistory.rst

+5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ Version history
33

44
This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
55

6+
**UNRELEASED**
7+
8+
- Fixed ``AssertionError`` when using ``nest-asyncio``
9+
(`#840 <https://github.com/agronholm/anyio/issues/840>`_)
10+
611
**4.7.0**
712

813
- Updated ``TaskGroup`` to work with asyncio's eager task factories

src/anyio/_backends/_asyncio.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -679,15 +679,16 @@ def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None):
679679

680680
class TaskStateStore(MutableMapping["Awaitable[Any] | asyncio.Task", TaskState]):
681681
def __init__(self) -> None:
682-
self._task_states = WeakKeyDictionary[asyncio.Task, TaskState]()
682+
self._task_states = WeakKeyDictionary[
683+
"asyncio.Task | Awaitable[Any]", TaskState
684+
]()
683685
self._preliminary_task_states: dict[Awaitable[Any], TaskState] = {}
684686

685687
def __getitem__(self, key: Awaitable[Any] | asyncio.Task, /) -> TaskState:
686-
assert isinstance(key, asyncio.Task)
687688
try:
688689
return self._task_states[key]
689690
except KeyError:
690-
if coro := key.get_coro():
691+
if coro := cast(asyncio.Task, key).get_coro():
691692
if state := self._preliminary_task_states.get(coro):
692693
return state
693694

@@ -696,16 +697,16 @@ def __getitem__(self, key: Awaitable[Any] | asyncio.Task, /) -> TaskState:
696697
def __setitem__(
697698
self, key: asyncio.Task | Awaitable[Any], value: TaskState, /
698699
) -> None:
699-
if isinstance(key, asyncio.Task):
700-
self._task_states[key] = value
701-
else:
700+
if isinstance(key, Coroutine):
702701
self._preliminary_task_states[key] = value
702+
else:
703+
self._task_states[key] = value
703704

704705
def __delitem__(self, key: asyncio.Task | Awaitable[Any], /) -> None:
705-
if isinstance(key, asyncio.Task):
706-
del self._task_states[key]
707-
else:
706+
if isinstance(key, Coroutine):
708707
del self._preliminary_task_states[key]
708+
else:
709+
del self._task_states[key]
709710

710711
def __len__(self) -> int:
711712
return len(self._task_states) + len(self._preliminary_task_states)

0 commit comments

Comments
 (0)