According to the PEP 484’s “Using None” part:
When used in a type hint, the expression
None
is considered equivalent totype(None)
.
However, I encountered a case where both don’t seem equivalent :
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))
It doesn’t pose me much problem to write type(None)
rather than simply None
, but I would’ve liked to understand the above error issued that seems to contradict the quote from PEP 484.
Snippet available for execution here.