51

Can you define the type hint for a variable defined with the with syntax?

with example() as x:
    print(x)

I would like to type hint the above to say that x is a str (as an example).

The only work around that I've found is to use an intermediate variable, but this feels hacky.

with example() as x:
    y: str = x
    print(y)

I can't find an example in the typing documentation.

10
  • 8
    Shouldnt type checkers be able to deduce the type of x as the return type of example().__enter__()?
    – pschill
    Feb 11, 2020 at 13:34
  • 2
    Why do you want to annotate x when it's is simply the return type of example.__enter__? Ideally you have annotated that method / function.
    – a_guest
    Feb 11, 2020 at 13:36
  • 1
    x isn't the return value of example; it's the return value of example().__enter__().
    – chepner
    Feb 11, 2020 at 13:36
  • 1
    Most methods I've found don't define a type hint for the return value.
    – Reactgular
    Feb 11, 2020 at 13:37
  • 1
    @Reactgular Then the solution is to create a stub file for that function, so the type checker can infer the type. Usually you annotate at the API boundaries, not inside. In this case it's clear the type comes from example. Annotating example.__enter__ means one annotation while with your approach you would have to annotate in all places where that context manager is used, plus in general how is a user supposed to know what the return type of an API is anyway if it isn't supplied?
    – a_guest
    Feb 11, 2020 at 13:40

2 Answers 2

57

PEP 526, which has been implemented in Python 3.6, allows you to annotate variables. The variable used in a with statement can be annotated like this:

x: str
with example() as x:
    [...]
5
  • 1
    This also works for other code blocks like for. Great answer, thank you.
    – Reactgular
    Feb 11, 2020 at 14:15
  • 1
    If the context manager doesn't hint what the __enter__ method will return, typing x doesn't serve any purpose. mypy will happily allow a value of any type to be bound to x.
    – chepner
    Feb 11, 2020 at 14:19
  • 1
    @chepner Yes you are right. PyCharm recognizes x as str in both cases, but mypy does not.
    – pschill
    Feb 11, 2020 at 14:27
  • I get error Name "x" already defined on line by mypy for second example
    – cikatomo
    Apr 23 at 23:46
  • @cikatomo You are right, I edited my answer and removed the second example. Seems to be a case of Where annotations aren't allowed
    – pschill
    Apr 24 at 7:38
16

Usually type annotations are placed at the API boundaries. In this case the type should be inferred from example.__enter__. In case that function doesn't declare any types, the solution is to create a corresponding stub file in order to help the type checker infer that type.

Specifically this means creating a .pyi file with the same stem as the module from which Example was imported. Then the following code can be added:

class Example:
    def __enter__(self) -> str: ...
    def __exit__(self, exc_type, exc_value, exc_traceback) -> None: ...
1
  • This one will fail miserably if class Example is inherited from some contextlib other class As these define def __enter__(self) -> Self so you now can never return anything other than self. Which is needed in 99% cases
    – user64204
    May 7 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.