Replies: 4 comments 1 reply
-
I can't think of any technical reason why this isn't allowed. Perhaps it's because class variable accesses typically don't include explicit class specialization. Using your example above, FWIW, pyright emits an error if you attempt to use a type variable within a |
Beta Was this translation helpful? Give feedback.
-
I forget that this limitation exists because it makes no sense WRT my mind-abstraction of Please provide solid reasoning or add the feature. |
Beta Was this translation helpful? Give feedback.
-
I'd like to throw my hat into the ring here, I'm not sure why this limitation exists, it seems inconsistent with the purpose of typings. Take for example this case where some abstract class View(ABC, Generic[Message, Result]):
# Limitation of the pep https://peps.python.org/pep-0526/#class-and-instance-variable-annotations
# see https://github.com/python/mypy/issues/5144#issuecomment-1001222212
# and https://github.com/python/typing/discussions/1424
accepts: ClassVar[Message] # type: ignore[misc]
returns: ClassVar[Result] # type: ignore[misc] The expected utilization might be something like class MyResult:
def __init__(self, result: list[dict]):
self.result = result
class MyView(View):
returns = MyResult
def serialize(self, result: list[dict]) -> MyResult:
return MyView.returns(result) I understand that if What steps would we need to take to have this limitation removed? It seems like a library such as |
Beta Was this translation helpful? Give feedback.
-
I believe the technical reason why this was not allowed is that different generic instantiations of the same class share a single runtime class object, which only has space for a single ClassVar of one type. You'd get type checker behavior like this: class Foo[T]:
x: ClassVar[T]
assert_type(Foo[int].x, int)
assert_type(Foo[str].x, str) But The practical use cases people come up with tend to involve generic base classes with non-generic child classes. That does make sense at runtime and in the type system, so it would be useful to allow. |
Beta Was this translation helpful? Give feedback.
-
I've read PEP 526 and searched around, but can't find any mention of why generics are not allowed in a
ClassVar
(just that they're not allowed). I was hoping to write a class like this:EDIT: I think I may have a misunderstanding of how to do what I want. I want to make a subclass like this:
class Bar(Foo[int]): ...
and useBar.Type
as a type annotation later on. Looks like this may not be possible?Beta Was this translation helpful? Give feedback.
All reactions