Today we got a bug report in mypy, that Literal[1] | Literal[2] is not supported: python/mypy#11426
Currently this happens on 3.10:
from typing import Literal
Literal[1, 2] | Literal[3]
# error: Unsupported left operand type for | ("object")
This happens because mypy treats | as a regular __or__ operator. And _SpecialForm does not have this method. We have two ways to solve this:
- Special case it in
mypy. This is quite easy, but I don't think that this is a good way
- Add
__or__ method to _SpecialForm type, just like it is done in cpython: https://github.com/python/cpython/blob/14a4fce457033412278ca9a056787db424310dc3/Lib/typing.py#L396-L397 This way we can be sure mypy will just work! 🎉
There are several notes:
- There are
_SpecialForms that raise TypeError when used with |. Example: Final | int. But, this happens because Final is not allowed for Union. But, operator is supported. So, I guess this should be handled by a typechecker itself
TypedDict is not special in typeshed:
|
# TypedDict is a (non-subscriptable) special form. |
|
TypedDict: object |
But, | is supported by it:
>>> from typing import TypedDict
>>> class My(TypedDict): ...
...
>>> My | int
__main__.My | int
TypeVar is a separate class, not a special form. But, we can use T | S in runtime as well.
I will send a PR with my proposal. We can work from there! 👋
Today we got a bug report in
mypy, thatLiteral[1] | Literal[2]is not supported: python/mypy#11426Currently this happens on 3.10:
This happens because
mypytreats|as a regular__or__operator. And_SpecialFormdoes not have this method. We have two ways to solve this:mypy. This is quite easy, but I don't think that this is a good way__or__method to_SpecialFormtype, just like it is done incpython: https://github.com/python/cpython/blob/14a4fce457033412278ca9a056787db424310dc3/Lib/typing.py#L396-L397 This way we can be suremypywill just work! 🎉There are several notes:
_SpecialForms that raiseTypeErrorwhen used with|. Example:Final | int. But, this happens becauseFinalis not allowed forUnion. But, operator is supported. So, I guess this should be handled by a typechecker itselfTypedDictis not special intypeshed:typeshed/stdlib/typing.pyi
Lines 57 to 58 in f4143c4
|is supported by it:TypeVaris a separate class, not a special form. But, we can useT | Sin runtime as well.I will send a PR with my proposal. We can work from there! 👋