[Python] Mypy doesn't derive the type from a bounded TypeVar correctly and expect the Parent...

Discussão em 'Python' iniciado por Stack, Agosto 20, 2025.

  1. Stack

    Stack Membro Participativo

    In a generic class with the type constraint by a TypeVar (SomeContext in the MWE) with a bound on an abstract class inheriting from BaseModel (Context in the MWE), mypy doesn't derive the type to all the subclass of the bound (DashboardContext and DefaultContext in the MWE), and uses the type var itself.

    In the following example, mypy errors with the following message:

    error: Argument 1 to "assert_exhaustiveness" has incompatible type "SomeContext"; expected "Never" [arg-type]


    from typing import Generic, NoReturn, TypeVar
    from pydantic import BaseModel
    from abc import ABC

    def assert_exhaustiveness(x: NoReturn) -> NoReturn:
    """Raise an exception to indicate that a case is not handled."""
    raise AssertionError("Exhaustiveness check failed, this case should be handled.")


    class Context(BaseModel, ABC):
    """Base class for contexts."""


    class DashboardContext(Context):
    """Context for a dashboard."""


    class DefaultContext(Context):
    """Default context for queries without a dashboard."""


    SomeContext = TypeVar("SomeContext", bound=Context)


    class ContextualizedAction(Generic[SomeContext]):
    """Contextualized Action."""

    def __init__(self, context: SomeContext) -> None:
    self.context = context

    def apply_action(self) -> str:
    """Apply the action in the context."""
    match self.context:
    case DashboardContext():
    return f"Applying action in {type(self.context)}"
    case DefaultContext():
    return f"Applying action in {type(self.context)}"
    case _:
    assert_exhaustiveness(self.context)



    I tried removing BaseModel, it didn't help (kept it for the MWE because I need it)

    Continue reading...

Compartilhe esta Página