According to PEP-526 (https://peps.python.org/pep-0526/#class-and-instance-variable-annotations)
Note that no type variable may occur within a ClassVar argument, at any nesting depth: ClassVar[T] is invalid, as is ClassVar[List[Set[T]]], whenever T denotes a type variable.
What is the reason for that limitation? The PEP doesn't explain it; maybe the Typing github archives contain the answer…
I ran into this when annotating a generic base class with a pair of members, an instance attribute containing a typed instance and a class attribute containing that instance's type:
class _TransportBase[Conn: (httpx.Client, httpx.AsyncClient), Cred: httpx.Auth](ABC):
base_url: str
connection: Conn
_credential: Cred
_credential_type: ClassVar[Type] # intended as ClassVar[Type[Cred]]
@property
def credential(self) -> Cred:
return self._credential
@credential.setter
@abstractmethod
def credential(self, incoming: Any):
if not isinstance(incoming, self._credential_type):
self._credential = self._credential_type(incoming)
else:
self._credential = incoming
With ClassVar limited this way, I must choose between explicitly declaring this attribute class-level and showing how its type relates to the type of _credential.
This early design is bound to change during revision. I'd welcome suggestions, though the question I'm asking here concerns ClassVar.