Skip to content

Internal error with TypeGuard and Literal-based union narrowing using StrEnum #18895

Description

@frilox042

Crash Report

When using TypeGuard to narrow a Literal-based union from a StrEnum, mypy raises an internal error.
I found a workaround, but I prefer my first implementation as it is more concise.

Traceback

main.py: error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
If this issue continues with mypy master, please report a bug at https://github.com/python/mypy/issues
version: 1.10.0
main.py: : note: please use --show-traceback to print a traceback when reporting a bug

To Reproduce

from typing import TypeGuard, Literal, TypeAlias
from enum import StrEnum

class Model(StrEnum):
    MODEL_A1 = 'model_a1'
    MODEL_A2 = 'model_a2'
    MODEL_B = 'model_b'

MODEL_A: TypeAlias = Literal[Model.MODEL_A1, Model.MODEL_A2]
MODEL_B: TypeAlias = Literal[Model.MODEL_B]

def is_model_a(model: str) -> TypeGuard[MODEL_A]:
    return model in (Model.MODEL_A1, Model.MODEL_A2)

def is_model_b(model: str) -> TypeGuard[MODEL_B]:
    return model == Model.MODEL_B

def process_model(model: MODEL_A | MODEL_B) -> int:
    return 42

# Works
def handle_1(model: Model) -> int:
    if is_model_a(model):
        return process_model(model)
    if is_model_b(model):
        return process_model(model)
    return 0

# Crashes
def handle_2(model: Model) -> int:
    if is_model_a(model) or is_model_b(model):  # ❌ This line causes a crash
        return process_model(model)
    return 0

# Crashes
def handle_3(model: Model) -> int:
    match model:
        case m if is_model_a(m) or is_model_b(m):  # ❌ Also crashes
            return process_model(m)
        case _:
            return 0

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12
  • Operating system and version: Linux 6.13.8

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions