Skip to content

asynccontextmanager with TypeVar leads to new warnings (regression) #16451

@DanielNoord

Description

@DanielNoord

Bug Report

Playground link:
https://mypy-play.net/?mypy=latest&python=3.11&gist=87e38e6e3483050ab69494a7086129cf

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import TypeVar

T = TypeVar("T")


@asynccontextmanager
async def func(arg: T) -> AsyncIterator[T | str]:
    if arg is None:
        yield arg
    else:
        yield ""


async def func2() -> None:
    async with func(arg="") as x:
        print(x)

This raises the new errors on master/1.7, but not on 1.6.1.

You can check it on the playground.

Running with --old-type-inference makes the errors go away so I'm tagging @ilevkivskyi as the blog post said they were involved in this new feature. Sorry if this is not appropriate.

Expected Behavior

No errors as I don't think is wrong. pyright also seems to think this is fine.

Actual Behavior

main.py:8: error: Argument 1 to "asynccontextmanager" has incompatible type "Callable[[T], AsyncIterator[T | str]]"; expected "Callable[[VarArg(Never), KwArg(Never)], AsyncIterator[Never]]"  [arg-type]
main.py:17: error: Need type annotation for "x"  [var-annotated]
main.py:17: error: Argument "arg" to "func" has incompatible type "str"; expected Never  [arg-type]
Found 3 errors in 1 file (checked 1 source file)

Your Environment

master

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions