pytype icon indicating copy to clipboard operation
pytype copied to clipboard

Support try/except ImportError

Open rchen152 opened this issue 7 years ago • 1 comments

The following is a common code pattern:

try:
  import foo
except ImportError:
  foo = <some fallback>

It's easy enough to add # pytype: disable=import-error on the import line, but we might be able to use the error checkpointing code to roll back import errors that occur inside a try/except block.

rchen152 avatar Sep 25 '18 19:09 rchen152

I had a similar problem importing the typing module:

try:
    from backports import typing
except ImportError:
    import typing

def foo() -> typing.Union[X, Y]:
    ...

There's no error from the import but it seems to not understand what typing refers to after, and gives me errors about typing.FOO claiming it could be Any:

File "myfile.py", line 6, in <module>: Invalid type annotation 'Any or Union[X, Y]' for return [invalid-annotation]
  Must be constant

If I delete the try/except then either import by itself works as expected, ~either import typing or from backports import typing~.

EDIT: Sorry, it's actually an issue about backports.typing, not the try/except. I realized from backports import typing by itself does not work as expected, it's just silently losing type information and getting typing: Any.

dbarnett avatar Aug 01 '20 21:08 dbarnett