Hello all,
Sorry to bother you again with the generic thing. Golang will soon release a
new version with Generics. I like their way of doing it. Like Rust, they don’t
bother with TypeVars. It makes you wonder why we are not doing something
similar in Python.
[T: Type] ——> T is invariant and Type is the bound. [T] is Ok.
[T_co:: Type] ——> T is covariant and Type is the bound. [T_co::] is Ok.
[T_contra::: Type] —-> T is contravariant and Type is the bound . [T_contra:::]
is Ok.
Or some other symbol next to : to distinguish the variance.
[T: Type1 | Type2] —-> T is invariant and Type1 and Type2 are the constraints.
Or anything else to communicate these are constraints (maybe enclose them in
parentheses — tuple)
Example:
class Indexable[T_co::](Protocol[T_co]):
def __getitem__(self, n: int) -> T_co: …
@dataclass
class AInt:
seq: list[int]
def __getitem__(self, n: int) -> Int:
return self.seq[n]
@dataclass
class BStr:
seq: list[str]
def __getitem__(self, n: int) -> str:
return self.seq[n]
def get[T: int | str](n: int, object: Indexable[T]) -> T:
return object[n]
get(1, AInt([1, 2])) # ok
get(1, BStr([“one”, “two”])) # ok
Abdulla
Sent from my iPhone
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/3EKKM6JEJYH2XN6OCIBUPCH7PLTEXVMN/
Code of Conduct: http://python.org/psf/codeofconduct/