1

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```
9
  • 2
    Why can't your just return self._coro.__aiter__() from your __aiter__ function, and do await self._coro.__anext__() in your __anext__ function? Jun 6, 2020 at 20:15
  • 1
    As you suspect, the part where you have "no idea what you're doing" is indeed incorrect. You cannot await the same coroutine instance more than once. async for works by calling (and awaiting) aiter.__anext__ in each iteration. In other words, your __aiter__ should call coro.__aiter__ before returning self, and store the result in (say) self._coro_iter. Then your __anext__ can just return await self._coro_iter.__anext__(). (Note the return, without it your __anext__ would just keep returning None.) Jun 7, 2020 at 8:41
  • 1
    @PaulCornelius Returning self._coro.__aiter__() from __aiter__ would be wrong because then AddFunctionality.__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. Jun 7, 2020 at 8:44
  • 1
    @user4815162342 Question for you: __aiter__ must return an asynchronous iterator but that doesn't have to be self. Client code later calls a.__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 where coro.__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'? Jun 8, 2020 at 18:28
  • 2
    @PaulCornelius shouldn't return expression not contain the "await'? If __anext__ is defined as async def, then it must return await bla.__anext__(). If it's defined as def, then it can get away with return bla.__anext__(). The two mostly equivalent, the only difference being in the timing of execution of the surrounding code. Say if you do x = a.__anext__(); <something>; await x, and a.__anext__ does something before delegating to bla.__anext__(), then defining a.__anext__ as sync or async will differ in whether that code is invoked before or after <something>. Jun 8, 2020 at 18:57

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.