Replies: 1 comment 1 reply
-
|
You’re very close — this is a classic case of “the generic parameter is not flowing through the subclass hierarchy”. What’s going wrong The key issue is here: class DirManager(Manager[Dir]): By inheriting from Manager[Dir], you are freezing T = Dir for all subclasses of DirManager. reveal_type(GitManager().create2()) tuple[Dir, Dir]Type checkers are doing exactly what the type hierarchy tells them to do. ✅ Correct pattern: make the intermediate class generic too You want the generic parameter to remain open until the leaf class. from future import annotations class Dir: class Git(Dir): T = TypeVar("T", bound=Dir) class Manager(Generic[T]): 🔑 Make DirManager generic instead of fixing T Concrete leaf classes finally bind the type ✅ Result (what you want) reveal_type(GitManager().create()) reveal_type(GitManager().create2()) tuple[Git, Git]This works correctly in mypy, pyright, and pyre. Why this works Manager[T] defines behavior DirManager[T] preserves the generic parameter GitManager finally binds T = Git create2() stays fully generic and does not need to be overridden This is the same pattern used by the standard library (collections, typing, asyncio, etc.). About ClassVar[type[T]] You’re also correct that: create: ClassVar[type[T]] is rejected by pyright/pyre — that’s intentional and specified behavior. Using a normal method override (as above) is the correct and portable solution. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a class-hierarchy and a matching class-hierarchy of managers for them:
Is it possible to get
GitManager().create2()to also return(Git, Git)instead of(Dir, Dir)without explicitly overwritingcreate2()in every sub-class?PS:
pyrightandpyreflydo not like the declaration of create:ClassVar[type[T]]and report#1424 has some more information about that. Using the alternative
def create(self) -> …as hinted in the comments does not make a difference regarding the return types.mypyandtyaccept it. See #1775 for hinting that.Beta Was this translation helpful? Give feedback.
All reactions