Thanks to visit codestin.com
Credit goes to github.com

Skip to content

New style unions and special forms #6219

Closed
@sobolevn

Description

@sobolevn

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:

  1. Special case it in mypy. This is quite easy, but I don't think that this is a good way
  2. 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! 👋

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions