Вы правы, подчеркнутые объекты не следует импортировать из typing
(и любой другой стандартной библиотеки), поскольку они рассматриваются как подробности реализации.
Если мы посмотрим на typing
module source :
# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
T = TypeVar('T') # Any type.
KT = TypeVar('KT') # Key type.
VT = TypeVar('VT') # Value type.
T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
# Internal type variable used for Type[].
CT_co = TypeVar('CT_co', covariant=True, bound=type)
# A useful type variable with constraints. This represents string types.
# (This one *is* for export!)
AnyStr = TypeVar('AnyStr', bytes, str)
Таким образом, даже не подчеркнутые TypeVar
s не должны импортироваться (кроме AnyStr
one). И да, AFAIK, мы должны определить их сами, если это необходимо.
Я не знаю ни одного стандартного способа сделать это, но лично я предпочитаю иметь модуль с только-type-hints-only, как
myproject / hints.py
from typing import TypeVar
...
Domain = TypeVar('Domain')
и впоследствии используйте его в других myproject модулях
from myproject.hints import Domain
...
def first(l: Sequence[Domain]) -> Domain:
return l[0]