mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Type annotation for `__await__` method.

Open trivialfis opened this issue 1 year ago • 2 comments

Bug Report

With the latest mypy 1.11.0, it reports errors for awaiting an awaitable object. For previous versions, there was no error.

To Reproduce

from typing import Any, Awaitable, Generator

class MyClass:
    def __init__(self) -> None:
        self.foo = "bar"

    def __await__(self) -> Generator["MyClass"]:
        yield self

async def fn() -> None:
    test = await MyClass()

Expected Behavior

No error, or a more concise error that uses the yield type of __await__ instead of __init__ (None).

Actual Behavior

Function does not return a value (it only ever returns None)  [func-returns-value]

Your Environment

  • Mypy version used: mypy 1.11.0 (compiled: yes)
  • Mypy configuration options from mypy.ini (and other config files):
[mypy]
ignore_missing_imports = True
disallow_untyped_defs = True
follow_imports = silent
  • Python version used: Python 3.11.9

trivialfis avatar Jul 31 '24 11:07 trivialfis

Shouldn't this be Generator[Any, None, "MyClass"]?

sobolevn avatar Aug 11 '24 19:08 sobolevn

Wouldn't it make MyClass the return type instead of the yield type?

trivialfis avatar Aug 12 '24 18:08 trivialfis

This will raise a RuntimeError: Task got bad yield

This is not a problem at all

from typing import Any, Generator, Self

class MyClass:
    def __init__(self) -> None:
        self.foo = "bar"

    def __await__(self) -> Generator[None, Any, Self]:
        yield None
        return self

AlanBogarin avatar Apr 06 '25 23:04 AlanBogarin

Closing per above - original code raises at runtime, suggested correction typechecks.

brianschubert avatar Apr 06 '25 23:04 brianschubert