Skip to content

aiter() and anext() call __aiter__ and __anext__ unbound #161394

Open

Description

@fedonman

Bug description:

Since aiter() and anext() were reimplemented in Python (gh-157361), they call __aiter__ and __anext__ unbound with the iterator as an argument, instead of binding them to the iterator as async for does. Anything that is not a plain function breaks, including unittest.mock:

from unittest import mock
aiter(mock.MagicMock())
TypeError: _get_async_iter.<locals>.__aiter__() takes 0 positional arguments but 1 was given
import asyncio
from unittest import mock

m = mock.MagicMock()
m.__anext__.return_value = 1
asyncio.run(anext(m))
m.__anext__.assert_awaited_once_with()
AssertionError: expected await not found.
Expected: __anext__()
  Actual: __anext__(<MagicMock id='138916121566848'>)

A staticmethod or another descriptor used as __aiter__ or __anext__ raises TypeError the same way, while async for over the same object works. An __anext__ defined only on the metaclass is now accepted as well. Both snippets pass on 3.14.

Expected: aiter() and anext() call these methods the same way async for does.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 5, 2026
  2. deadlovelll commented on Nov 5, 2026

    @deadlovelll
    Contributor

    hi @fedonman! If you don't mind i can look at this and solve it =)

  3. picnixz commented on Nov 5, 2026

    @picnixz
    Member
  4. gvanrossum commented on Nov 5, 2026

    @gvanrossum
    Member

    Have you tried this with anything other than a mock? Or is the mock the only thing that fails? Because the general rule for calling dunder methods is that, indeed, we look up the unbound dunder on the class (which searches for it through the MRO) and call it with the instance as first argument -- this is done because we don't want to incur the additional lookup overhead on the instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions