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

Conditional import based on python version check doesn't work #4182

Closed
Dr-Irv opened this issue Nov 11, 2022 · 1 comment
Closed

Conditional import based on python version check doesn't work #4182

Dr-Irv opened this issue Nov 11, 2022 · 1 comment
Labels
as designed Not a bug, working as intended

Comments

@Dr-Irv
Copy link

Dr-Irv commented Nov 11, 2022

Describe the bug
If you have a conditional import based on the python version, pyright still says the import is missing.

This comes up in pandas-stubs where we have some dependent libraries that are not ready for python 3.11 yet, so we want to conditionally import them.

To Reproduce

import sys

PY310 = sys.version_info >= (3, 10)
reveal_type(PY310)

if not PY310:
    import foobar

pyright reports:

pyvertst.py:7:12 - error: Import "foobar" could not be resolved (reportMissingImports)
pyvertst.py:4:13 - information: Type of "PY310" is "Literal[True]"

Expected behavior
pyright should not try to do the import based on the version test.

VS Code extension or command-line
command line pyright version 1.1.278
Try the above in a python 3.10 environment.

@erictraut
Copy link
Collaborator

This is expected. You cannot use a variable for the conditional. You need to use the sys.version_info >= (3, 10) directly in the if statement.

Pyright (and other type checkers) look for very specific conditional expression forms in the first stage of analysis (the "binder"), which occurs long before the types of any symbols are evaluated.

PEP 484 indicates "type checkers are expected to understand simple version and platform checks" and then gives a few examples. Pyright and all other type checkers support these expression forms.

You'll need to change the above code to the following for it to work in pyright (and other type checkers):

import sys

if not sys.version_info < (3, 10):
    import foobar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
as designed Not a bug, working as intended
Projects
None yet
Development

No branches or pull requests

2 participants