-
Notifications
You must be signed in to change notification settings - Fork 288
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. # 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]
Beta Was this translation helpful? Give feedback.
All reactions
There's also MYPY = False; if MYPY: ... if you're using mypy
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 ImportError. So I don't think there is a better way to do this.
Beta Was this translation helpful? Give feedback.
All reactions
-
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.
Beta Was this translation helpful? Give feedback.
All reactions
-
There's also MYPY = False; if MYPY: ... if you're using mypy
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1
-
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
Beta Was this translation helpful? Give feedback.
All reactions
-
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.
Beta Was this translation helpful? Give feedback.