Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How should Pyright consider typing stubs with try-excepted imports? #1358

Closed
decorator-factory opened this issue Jan 11, 2021 · 2 comments
Closed

Comments

@decorator-factory
Copy link

decorator-factory commented Jan 11, 2021

immutables repo: https://github.com/MagicStack/immutables/blob/master/immutables/__init__.py

has this code in __init__.py:

try:
    from ._map import Map
except ImportError:
    from .map import Map

The project has a _map.pyi, but no map.pyi. Pyright thinks that only map is ever imported, so it doesn't use _map.pyi.

This is fixed by:

try:
    from ._map import Map
except ImportError:
    if TYPE_CHECKING:
        from ._map import Map
    else:
        from .map import Map

or:

if TYPE_CHECKING:
    from ._map import Map
else:
    try:
        from ._map import Map
    except ImportError:
        from .map import Map

but maybe Pyright should somehow use _map's typing stub in that case? Or would you say that libraries should just use the second variant, or provide typing stubs for module instead of _module?

@erictraut
Copy link
Collaborator

Conditional (dynamic) imports are very difficult for a static analyzer. When resolving an import symbol, Pyright uses the last declaration of the symbol in the file regardless of whether the import statement is in an if/else or try/except block. If that order doesn't work for you, you can use a a TYPE_CHECKING conditional to hide declarations that you don't want pyright to consider.

Another option is to create a local stub alias. In your case you could create a map.pyi that re-exports all the symbols from _map.pyi.

@decorator-factory
Copy link
Author

That makes sense. Thank you!

s-weigand added a commit to s-weigand/verbose-version-info that referenced this issue Feb 19, 2021
When working with Python >= 3.8 PyLance fails to pick up the proper types, since it always uses the last last definition of a symbol.
See microsoft/pyright#1358
heejaechang pushed a commit to heejaechang/pyright that referenced this issue Nov 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants