Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Using type hint comments without having to import the typing module #1698

Answered by hauntsaninja
huntfx asked this question in Q&A
Discussion options

I'm still having to use Python 2, so a module I'm working on is compatible between Python 2 and 3.

If a type hint defined as a comment uses one of the typing module classes (eg. # type: (int) -> List[int]), then it will raise an error if from typing import List is not present in the file, which feels weird since it's only required in the comment and nowhere else in the code.

It feels very cumbersome to do a try/except on the import on every single file. Is there a better way I can do this without the import?

try:
 from typing import List
except ImportError:
 pass
def func(x, yList):
 # type: (int, List[int]) -> List[int]
 return [x + y for y in yList]
You must be logged in to vote

There's also MYPY = False; if MYPY: ... if you're using mypy

Replies: 2 comments 3 replies

Comment options

Using Python 2 you will have some pain points. When using Python 3, you would usually guard the imports behind a "typing.TYPE_CHECKING" conditional. (Which is still a bit painful.) But that won't work with Python 2, of course, since you'd still need to catch the ImportError. So I don't think there is a better way to do this.

You must be logged in to vote
3 replies
Comment options

Isn't if False: # TYPE_CHECKING the thing you can use pre Python 3.5? I seem to remember something like this. Then you don't need to catch any import errors or install the backported package.

Comment options

There's also MYPY = False; if MYPY: ... if you're using mypy

Answer selected by huntfx
Comment options

Thanks, I'm happy with that as a solution. Using if False fixes mypy, but causes pylance to complain about undefined variables. if MYPY satisfies both.

I've settled on this for now:

from .. import exceptions, types, utils
if utils.TYPE_CHECKING:
 from typing import List
Comment options

On Python 2 you can pip install typing (https://pypi.org/project/typing/). We stopped maintaining it when Python 2.7 reached its end-of-life, so it won't have some of the newer typing features, but it has the basics.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /