aclosing_iter#
- class mobu.asyncio.aclosing_iter(thing)#
Bases:
AbstractAsyncContextManager
,Generic
Automatically close async iterators that are generators.
Python supports two ways of writing an async iterator: a true async iterator, and an async generator. Generators support additional async context, such as yielding from inside an async context manager, and therefore require cleanup by calling their
aclose
method once the generator is no longer needed. This step is done automatically by the async loop implementation when the generator is garbage-collected, but this may happen at an arbitrary point and produces pytest warnings saying that theaclose
method on the generator was never called.This class provides a variant of
contextlib.aclosing
that can be used to close generators masquerading as iterators. Many Python libraries implement__aiter__
by returning a generator rather than an iterator, which is equivalent except for this cleanup behavior. Async iterators do not require this explicit cleanup step because they don’t support async context managers inside the iteration. Since the library is free to change from a generator to an iterator at any time, and async iterators don’t require this cleanup and don’t haveaclose
methods, theaclose
method should be called only if it exists.- Parameters:
thing (
TypeVar
(T
, bound=AsyncIterator
))