Bogus bad-return-type error when combining `try`-`finally` with `with`
Reproducible example:
import contextlib
import typing
def f() -> int:
try:
with contextlib.nullcontext():
return 42
finally:
pass # Line 9
Running pytype (2021.05.25) on the above code prints:
File "/path/to/example.py", line 9, in f: bad return type [bad-return-type]
Expected: int
Actually returned: None
pytype seems to have the misbelief that the finally block will do the equivalent of return None. Note that the error disappears if I remove the with line.
same
Hi,
We have a similiar issue, but i didnt get your case.
Isn't this the expected behaviour since in the case that execution goes in to finally, the function does indeed returns None.
Similiarly, what difference do we expect from the usage of with? I suppose it is more interesting that removing with actually fixes the error.
Isn't this the expected behaviour since in the case that execution goes in to finally, the function does indeed returns None.
No. If you run the above code, you'll see invoking f() returns 42 not None. In contrast, if finally had an explicit return None statement, then invoking f() indeed would return None.
I don't believe that this has anything to do with with. This also reproduces in 2023.07.28:
def foo() -> str:
try:
return "a"
except Exception:
return "b"
finally:
print("finally")
pytype reports bad-return-type because the finally block "doesn't return".