Replies: 1 comment 2 replies
-
I think your instincts are leading you in the right direction. The problem is that type variables cannot be used in class variable declarations. That's because all specialized instances of a class share the same class object. You could do something like this, which stores the type as an instance variable. Code sample in pyright playground from collections.abc import Iterator
import pathlib
class PathsBase[T: pathlib.Path]:
def __init__(self, _type: type[T]) -> None:
self._type = _type
def __iter__(self) -> Iterator[T]:
yield self._type(".")
class Paths(PathsBase[pathlib.Path]):
def __init__(self) -> None:
super().__init__(pathlib.Path)
class PosixPaths(PathsBase[pathlib.PosixPath]):
def __init__(self) -> None:
super().__init__(pathlib.PosixPath)
items = list(Paths())
items = list(PosixPaths())
posix_items = list(PosixPaths())
item: pathlib.PosixPath = posix_items[0] |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Let's say I have the following classes:
Is it possible to make
Paths
inherit fromIterable
such that it can representIterable[pathlib.Path]
andPosixPaths
can represent anIterable[pathlib.PosixPath]
? I'm needing to useSequence
instead ofIterable
in my implementation, but I'm usingIterable
in this example for brevity and I'm assuming that the solution forIterable
can be easily applied toSequence
.Is it possible for the types to be defined such that
PosixPaths
does not need to redefine__iter__
?My instinct to solve the above issues is to want to do something like the following:
I'm using mypy 1.10.0 (compiled: yes) with Python 3.12.4.
Beta Was this translation helpful? Give feedback.
All reactions