Skip to content

Instantly share code, notes, and snippets.

View kristjanvalur's full-sized avatar
💭
normal

Kristján Valur Jónsson kristjanvalur

💭
normal
View GitHub Profile
@kristjanvalur
kristjanvalur / aclosing.py
Created April 24, 2023 09:26
An asyncronous iterator which automatically closes the underlying iterator when done
#
# Python's `async for` only iterates and won't call `aclose()` on an Async Generator when done.
# Although `aclose()` is automatically scheduled to happen when the iterator goes out of scope, this will
# happen on a different Task.
# If iteration over an Async Generator is interrupted somehow, or left unfinished, that can be problematic
import contextlib
@contextlib.asynccontextmanager
async def aclosingiterator(iterable):
iter = iterable.__aiter__()

Keybase proof

I hereby claim:

  • I am kristjanvalur on github.
  • I am kristjanvalur (https://keybase.io/kristjanvalur) on keybase.
  • I have a public key ASDQL16PN2-6wovxkuDDvtAInd9T2yEY12XzCZawsDHTwwo

To claim this, I am signing this object: