I am working on a project to run File I/O in a separate thread, however I wanted to make an improvement to my open() coroutine. Before adding the @helper
, in order to use the functionality of the _Filer class, it was necessary to do the following:
async with await open('myfile'): #works fine, just not preferred
...
async for i in await open('file.txt'): #also works fine
...
The whole point of the AddFunctionality
class and the helper
decorator is to await
the coroutine for the user, so they can use it like so:
async with open('file.txt'): #this works
...
async for i in open('file.txt'): #this is completely broken
...
Fortunately, everything except for __aiter__
and __anext__
(the components of an async for
statement) are working perfectly. I am just not sure how I can await self._coro
in the context of __aiter__
and __anext__
. Any help is appreciated.
from collections.abc import Coroutine
from functools import wraps
class AddFunctionality(Coroutine):
__slots__ = ("_coro", "_obj")
def __init__(self, coro):
self._coro = coro
self._obj = None
print('calling init')
def send(self, value):
print('calling send')
return self._coro.send(value)
def throw(self, typ, val=None, tb=None):
print('calling throw')
if val is None:
return self._coro.throw(typ)
if tb is None:
return self._coro.throw(typ, val)
return self._coro.throw(typ, val, tb)
def close(self):
print('calling close')
return self._coro.close()
def __await__(self):
print('calling await')
return self._coro.__await__()
async def __aenter__(self):
print('calling aenter')
self._obj = await self._coro
return self._obj
async def __aexit__(self, exc_type, exc, tb):
print('calling aeixt')
await self._obj.close()
self._obj = None
def __aiter__(self):
return self #
async def __anext__(self):
await self._coro # I have no idea what I'm doing
#error: RuntimeError: cannot reuse already awaited coroutine
def helper(method):
@wraps(method)
def wrapper(*args, **kwargs) -> AddFunctionality:
return AddFunctionality(method(*args, **kwargs))
return wrapper
@helper
async def open(*args, **kwargs):
f = _Filer(*args, **kwargs)
#keep in mind that the `_Filer` class has __aiter__, __anext__, __aenter__, and __aexit__ attributes
await f.returner() #this just opens the file up. it's not relevant to my question
return f```
self._coro.__aiter__()
from your__aiter__
function, and doawait self._coro.__anext__()
in your__anext__
function?async for
works by calling (and awaiting)aiter.__anext__
in each iteration. In other words, your__aiter__
should callcoro.__aiter__
before returning self, and store the result in (say)self._coro_iter
. Then your__anext__
can justreturn await self._coro_iter.__anext__()
. (Note thereturn
, without it your__anext__
would just keep returning None.)self._coro.__aiter__()
from__aiter__
would be wrong because thenAddFunctionality.__anext__
would never get called. Maybe that's ok if the OP just wants to combine iteration and context management, but it's hard to tell.__aiter__
must return an asynchronous iterator but that doesn't have to beself.
Client code later callsa.__anext__()
, where a is the object returned by__aiter__
. In that case, no__anext__
is needed. The OP's requirements are indeed fuzzy here as you point out. Your solution seems better, however, since it also handles the case wherecoro.__aiter__()
does not return the coro object itself but some other object. Also,__anext__
is supposed to return an awaitable object, so shouldn't your (any my) return expression not contain the "await'?__anext__
is defined asasync def
, then it mustreturn await bla.__anext__()
. If it's defined asdef
, then it can get away withreturn bla.__anext__()
. The two mostly equivalent, the only difference being in the timing of execution of the surrounding code. Say if you dox = a.__anext__(); <something>; await x
, anda.__anext__
does something before delegating tobla.__anext__()
, then defininga.__anext__
as sync or async will differ in whether that code is invoked before or after<something>
.