Skip to content

async with usage with asynccontextmanager-decorated function results in Unknown #1804

@sharkdp

Description

@sharkdp

Consider the following example, where the usage of a asynccontextmanager-decorated function in an async with statement results in an Unknown type:

from contextlib import asynccontextmanager
from typing import AsyncGenerator

class Session: ...

@asynccontextmanager
async def connect() -> AsyncGenerator[Session]:
    yield Session()


async def main():
    async with connect() as session:
        # TODO: should be `Session`
        reveal_type(session)  # revealed: Unknown

https://play.ty.dev/8f142494-1d12-48fd-8ea5-005b1bdf62dd

The problem is that we currently infer () -> _AsyncGeneratorContextManager[Unknown, None] for connect. The signature of asynccontextmanager is:

def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]

so this requires generics-solver support for Callable and generic protocols.

Note that we have a test for this here: https://github.com/astral-sh/ruff/blob/a364195335eb920ff429c43832c4ee464051ea9a/crates/ty_python_semantic/resources/mdtest/with/async.md?plain=1#L203-L222

Metadata

Metadata

Labels

genericsBugs or features relating to ty's generics implementation

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions