async enumeration - possible?

Steve D'Aprano steve+python at pearwood.info
Wed Nov 30 19:05:38 EST 2016


On Wed, 30 Nov 2016 07:51 pm, Ian Kelly wrote:

> On Wed, Nov 30, 2016 at 1:29 AM, Frank Millman <frank at chagford.com> wrote:

>> But I found it easy to write my own -
>>
>> async def anext(aiter):
>>    return await aiter.__anext__()
> 
> Even simpler:
> 
> def anext(aiter):
>     return aiter.__anext__()


With very few exceptions, you shouldn't be calling dunder methods directly.

Ideally, you should have some function or operator that performs the call
for you, e.g. next(x) not x.__next__().

One important reason for that is that the dunder method may be only *part*
of the protocol, e.g. the + operator can call either __add__ or __radd__;
str(x) may end up calling either __repr__ or __str__.

If such a function doesn't exist, then it's best to try to match Python's
usual handling of dunders as closely as possible. That means, you shouldn't
do the method lookup on the instance, but on the class instead:

    return type(aiter).__anext__()

That matches the behaviour of the other dunder attributes, which normally
bypass the instance attribute lookup.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list