PEP-526(https://peps.python.org/pep-0526/#class-and-instance-variable-annotations)说
ClassVar 参数里不能包含任何类型变量,无论嵌套多深都不行。如果 T 是类型变量,ClassVar[T] 和 ClassVar[List[Set[T]]] 都无效。
为什么会有这个限制?PEP 本身没有解释,也许 Typing github 的历史记录里有答案……
我给一个带有两个成员的泛型基类加类型注解时遇到了这个问题,一个是保存特定类型实例的实例属性,另一个是保存该实例类型本身的类属性。
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
由于 ClassVar 有这样的限制,我必须在明确声明这个属性属于类,和表达它的类型与 _credential 类型的关系之间做出选择。
这只是早期草稿,修改时设计肯定会变。欢迎提出建议,不过我在这里问的是 ClassVar 本身。