Skip to content

Type annotations on with statements #1356

Closed
@rwbarton

Description

@rwbarton

We might not always be able to infer the type of the variable bound by a with statement, just like we might not always be able to infer the type of a variable being assigned to for the first time. For this minimal example

from typing import TypeVar
from contextlib import ContextManager
T = TypeVar('T')
def g() -> ContextManager[T]: ...

with g() as x:
    pass

mypy reports

with.py:6: error: Need type annotation for variable

It would be nice to be able to write, for example,

with g() as x:  # type: int

declaring the type of x. This is currently rejected by mypy as a parse error.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions