Suggestion: Allow free type variables in type variable bounds that permeate beyond
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 1.8k
- Forks
- 302
- Ø Merge
- 23 Std.
- Gemergte PRs (30 T.)
- 8
Beschreibung
Suppose we have the following code:
T_co = TypeVar("T_co", covariant=True)
class CanProduce(Protocol[T_co]):
def produce(self) -> T_co:
...
T_in = TypeVar("T_in")
U = TypeVar("U")
@dataclass
class Container(Generic[T_in]):
value: T_in
def produce_from_value(self: Container[CanProduce[U]]) -> U:
return self.value.produce()
This code has an undesirable property: Since T_in is invariant, produce_from_value can only be called on instances of Container whose type parameter is exactly CanProduce[U], for some U:
class IntProducer(CanProduce[int]):
def produce(self) -> int:
return 42
c: Container[IntProducer] = Container(IntProducer())
c.produce_from_value() # this produces a type error
It would be ideal if we could communicate that in this method (which need not be an instance method, it could be a discrete function also), the type parameter behaves as though it were covariant, where any subtype of CanProduce[U] is valid.
In fact, there exists a mechanism for doing this in other situations. Consider if we have the following non-generic protocol:
class SupportsIndex(Protocol):
def __index__(self) -> int:
...
We can then make a method index_from_value that works with all subtypes of SupportsIndex:
SI = TypeVar("SI", bound=SupportsIndex)
@dataclass
class Container(Generic[T_in]):
value: T_in
def index_from_value(self: Container[SI]):
return self.value.__index__
Now, the following is valid:
c: Container[int] = Container(27)
c.index_from_value()
Unfortunately, this method cannot be used with generic protocols, because the following is invalid:
U = TypeVar("U")
CPU = TypeVar("CPU", bound=CanProduce[U]) # this produces a type error
I suggest altering the restriction to allow this trick to work.
Beitragsleitfaden
Für dieses Repository ist kein Beitragsleitfaden indexiert
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit den generischen Beispielen für protocol, Container und TypeVar im Issue und vergleiche sie anschließend mit dem nicht generischen Fall SupportsIndex. Das Issue ist erst dann bereit für die Bearbeitung, wenn die vorgeschlagene Änderung der Einschränkung und ihr Verhalten für Subtypen klar genug spezifiziert sind, um sie beurteilen zu können.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 25/100