MyPy leitet den Typ nicht korrekt von einem begrenzten Typevar ab und erwartet die übergeordnete Klasse (eine pydantischPython

Python-Programme
Anonymous
 MyPy leitet den Typ nicht korrekt von einem begrenzten Typevar ab und erwartet die übergeordnete Klasse (eine pydantisch

Post by Anonymous »

in einer generischen Klasse mit der Typ -Einschränkung durch einen typarischen (

Code: Select all

SomeContext
in der MWE) mit einer an eine abstrakte Klasse gebundene Klasse von Basemodel (

Code: Select all

Context
In der MWE) leitet MyPy den Typ nicht an die gesamte Unterklasse der Grenze ab (

Code: Select all

DashboardContext
und defaultContext im MWE) und verwendet den Typ Var selbst.error: Argument 1 to "assert_exhaustiveness" has incompatible type "SomeContext"; expected "Never" [arg-type]
< /code>
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)

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

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post