Using type hint comments without having to import the typing module #1698
-
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. 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] |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
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 |
Beta Was this translation helpful? Give feedback.
-
On Python 2 you can |
Beta Was this translation helpful? Give feedback.
There's also
MYPY = False; if MYPY: ...
if you're using mypy