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.
x
as the return type ofexample().__enter__()
?x
when it's is simply the return type ofexample.__enter__
? Ideally you have annotated that method / function.x
isn't the return value ofexample
; it's the return value ofexample().__enter__()
.example
. Annotatingexample.__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?