According to the docs, constrained TypeVars should match exactly.
However, when using custom classes, the behaviour seems counterintuitive:
from dataclasses import dataclass
from typing import Generic, TypeVar
@dataclass
class PrinterConnection:
name: str = ""
@dataclass
class WiFiPrinterConnection(PrinterConnection):
name = "WiFi"
@dataclass
class USBPrinterConnection(PrinterConnection):
name = "USB"
@dataclass
class USBTypeCPrinterConnection(USBPrinterConnection):
name = "USB-C"
Connection = TypeVar("Connection", USBPrinterConnection, WiFiPrinterConnection)
@dataclass
class Printer(Generic[Connection]):
connection: Connection
Printer(WiFiPrinterConnection()) # No Warning - As Expected
Printer(USBPrinterConnection()) # No Warning - As Expected
Printer(USBTypeCPrinterConnection()) # No Warning - NOT Expected
In this example, USBTypeCPrinterConnection is not one of the types defined in the the TypeVar and yet no warning is thrown.
My questions are:
- Why isn't a Warning being thrown here?
- Is there a way to allow for particular classes and not its subclasses?
These examples were done with Python 3.10 and Pylance for the type checking.