Skip to content

Type annotations on with statements #1356

Closed
@rwbarton

Description

@rwbarton
Contributor

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.

Activity

gvanrossum

gvanrossum commented on Apr 8, 2016

@gvanrossum
Member

Yeah, PEP 484 says this should work. (Also for a for loop.)

gvanrossum

gvanrossum commented on Apr 8, 2016

@gvanrossum
Member

Actually we already have an issue for this. Closing as dupe of #892.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @rwbarton@gvanrossum

        Issue actions

          Type annotations on `with` statements · Issue #1356 · python/mypy