При использовании в подсказке типа выражение None считается эквивалентным type(None).
Однако я столкнулся со случаем, когда оба варианта не кажутся эквивалентными:
Код: Выделить всё
from typing import Callable, NamedTuple, Type, Union
# I define a set of available return types:
ReturnType = Union[
int,
None,
]
# I use this Union type to define other types, like this callable type.
SomeCallableType = Callable[..., ReturnType]
# But I also want to store some functions metadata (including the function's return type) in a `NamedTuple`:
class FuncInfos(NamedTuple):
return_type: Type[ReturnType]
# This works fine:
fi_1 = FuncInfos(return_type=int)
# But this issues an error:
# main.py:21: error: Argument "return_type" to "FuncInfos" has incompatible type "None"; expected "type[int] | type[None]" [arg-type]
# Found 1 error in 1 file (checked 1 source file)
fi_2 = FuncInfos(return_type=None)
# But this works fine:
fi_3 = FuncInfos(return_type=type(None))
Фрагмент доступен для выполнения здесь.
EDIT : На самом деле, похоже, это сводится к следующему:
Код: Выделить всё
from typing import Type
a: Type[None]
# This seems to cause an issue:
# main.py:4: error: Incompatible types in assignment (expression has type "None", variable has type "type[None]") [assignment]
# Found 1 error in 1 file (checked 1 source file)
a = None
# This seems to work:
a = type(None)
Подробнее здесь: https://stackoverflow.com/questions/786 ... e-analysis