-
I am writing a certain data structure. if I just added into a collection, I want to be able to type safely use the subtype of the data. example (obviously not currently working, but demonstrates the idea): from __future__ import annotations
from typing import Final, Generic, TypeVar
T = TypeVar("T")
U = TypeVar("U", bound=T, covariant=True)
S = TypeVar("S", bound=T)
# link in a list with data types T, this one is a U: T
class LinkNode(Generic[T, U]):
data: Final[U]
next: LinkNode[T, T] | None = None
def __init__(self, data: U) -> None:
self.data = data
# goal: callers know node.add_next(s).data is S
def add_next(self, data: S) -> LinkNode[T, S]:
n: LinkNode[T, S] = LinkNode(data)
self.next = n
return n |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
See: #1226 This has been requested many times, but since this feature is a type of higher kinded types (HKT) this is non-trivial and has many side-effects that need to be considered carefully in the design of such a feature. So far nobody has stepped up to do the hard work of writing up a specification/PEP that resolves those issues. There are many languages with no support for HKTs at all, due to the inherent risk of introducing really bad soundness holes and the difficulty of reasoning about those HKTs. |
Beta Was this translation helpful? Give feedback.
See: #1226
This has been requested many times, but since this feature is a type of higher kinded types (HKT) this is non-trivial and has many side-effects that need to be considered carefully in the design of such a feature. So far nobody has stepped up to do the hard work of writing up a specification/PEP that resolves those issues.
There are many languages with no support for HKTs at all, due to the inherent risk of introducing really bad soundness holes and the difficulty of reasoning about those HKTs.