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 via try-except renders error for imported type #8319

Closed
tuukkamustonen opened this issue Jan 23, 2020 · 2 comments
Closed

Comments

@tuukkamustonen
Copy link

I'm running python 3.5 (mypy 0.761). TypedDict is not in typing so I have typing_extensions installed (for python < 3.8).

However, the library I'm building supports python up to 3.8, which has TypedDict built-in so I might as well use that.

So I tried conditional import:

try:
    from typing import TypedDict  # type: ignore
except ImportError:
    from typing_extensions import TypedDict

Foo = TypedDict('Foo', {
    'id': str,
})

def whatever(data: Foo) -> None:
    pass

Results in:

typetest.py:12: error: Variable "typetest.Foo" is not valid as a type

Adjusting the import as so makes the problem go away:

import sys
if sys.version_info >= (3, 8):
    from typing import TypedDict
else:
    from typing_extensions import TypedDict

https://mypy.readthedocs.io/en/stable/common_issues.html#python-version-and-system-platform-checks doesn't at least directly suggest to use this style for imports, though. What is the proper/preferred way to do conditional imports?

@JelleZijlstra
Copy link
Member

Yes, mypy should ideally support the pattern you tried. I am pretty sure there is already an open issue about this, but I can't find it right now.

@ilevkivskyi
Copy link
Member

This is essentially a duplicate of #1297

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

3 participants