Skip to content

Accessing dunders via type object produces TypeVar clashes #14814

Closed
@oremanj

Description

@oremanj

Consider the following code:

from typing import AsyncIterator, TypeVar

T = TypeVar("T")

async def anext_via_instance(it: AsyncIterator[T]) -> T:
    return await it.__anext__()

async def anext_via_type(it: AsyncIterator[T]) -> T:
    anext = type(it).__anext__
    return await anext(it)

mypy happily accepts anext_via_instance, but in anext_via_type it fails with:

main.py:10: error: Incompatible return value type (got "_T_co", expected "T")  [return-value]
main.py:10: error: Argument 1 has incompatible type "AsyncIterator[T]"; expected "AsyncIterator[_T_co]"  [arg-type]

If I add a reveal_type(anext) in anext_via_type:

main.py:10: note: Revealed type is "def (self: typing.AsyncIterator[_T_co`1]) -> typing.Awaitable[_T_co`1]"

This behavior doesn't seem to be a recent change; it showed up on every version I spot-checked on the playground, and is still present on master. From the error message it looks like some kind of issue with TypeVar inference, but I'm not an expert.

(I'm trying to write something like anext_via_type in order to mimic the interpreter's behavior accessing a magic method in a specific circumstance; it won't accept an instance attribute, only a class attribute, so I don't want to accept an instance attribute either.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions