pytype icon indicating copy to clipboard operation
pytype copied to clipboard

Bogus bad-return-type error when combining `try`-`finally` with `with`

Open jamesderlin opened this issue 4 years ago • 4 comments

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.

jamesderlin avatar Jun 05 '21 07:06 jamesderlin

same

yasarutkuu avatar Jun 08 '21 12:06 yasarutkuu

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.

Deniz97 avatar Jun 08 '21 12:06 Deniz97

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.

jamesderlin avatar Jun 08 '21 17:06 jamesderlin

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".

bbenne10 avatar Aug 10 '23 20:08 bbenne10