Skip to content

Conditional import via try-except renders error for imported type #8319

Closed

Description

@mtvx

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?

Activity

  1. JelleZijlstra commented on Jan 23, 2020

    @JelleZijlstra
    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.

  2. ilevkivskyi commented on Jan 25, 2020

    @ilevkivskyi
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions