Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tagged unions support #2160

Closed
mariusmuja opened this issue Aug 7, 2021 · 3 comments
Closed

Tagged unions support #2160

mariusmuja opened this issue Aug 7, 2021 · 3 comments
Labels
addressed in next version Issue is fixed and will appear in next published version enhancement request New feature or request

Comments

@mariusmuja
Copy link

Is your feature request related to a problem? Please describe.

The following code uses tagged unions with Literal integer as discriminant:

from typing import Tuple, Union, Literal

MsgA = Tuple[Literal[1], str]
MsgB = Tuple[Literal[2], float]

Msg = Union[MsgA, MsgB]

def handle_a(a: MsgA):
    pass

def handle_b(b: MsgB):
    pass


def handle(m: Msg):
    if m[0] == 1:
        handle_a(m)
    elif m[0] == 2:
        handle_b(m)

This type checks successfully with mypy as documented here (https://mypy.readthedocs.io/en/stable/literal_types.html#tagged-unions), however this type narrowing pattern is not supported by pyright.

Describe the solution you'd like

It would be great if pyright would also support this type narrowing pattern.

@mariusmuja mariusmuja added the enhancement request New feature or request label Aug 7, 2021
@erictraut
Copy link
Collaborator

This feature will be included in the next release of pyright and pylance.

@erictraut erictraut added the addressed in next version Issue is fixed and will appear in next published version label Aug 7, 2021
@mariusmuja
Copy link
Author

Thank you for adding this feature so quickly!

With this I can now remove lots of if TYPE_CHECKING: hacks from the code.

@erictraut
Copy link
Collaborator

This is addressed in pyright 1.1.161, which I just published. It will also be included in the next release of pylance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
addressed in next version Issue is fixed and will appear in next published version enhancement request New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants