Open
Description
Reading through the discussion at python/typing#59, there was an example that had TypeVar
bound that referenced itself. Is this intended to be eventually implemented? The actual PEP just has a bare Comparable
.
A motivating example (from the Java world) is discussed here, in the context of their Enum
. An example in Python:
from typing import Generic, Optional, Tuple, TypeVar
# Would like to write bound='TypedCons[T, V]' here, where T is self-referential
T = TypeVar('T', bound='TypedCons')
V = TypeVar('V')
class TypedCons(Generic[T, V]):
def __init__(self, value: V, cdr: Optional[T]=None) -> None:
self.value = value
self.cdr = cdr
def first_two(self) -> Tuple[T, T]:
# Fails without cast with "Incompatible return value type: expected Tuple[T`1, T`1], got Tuple[example.TypedCons[T`1, V`2], T`1]"
return self, self.cdr
class IntCons(TypedCons['IntCons', int]):
pass
# Recursive bound would reject this
class BadCons(TypedCons['IntCons', str]):
pass
If I try to write the recursive bound, I get:
example.py:3: error: Invalid type "example.T"
A similar example where this is needed is at https://github.com/smallnamespace/pymcts/blob/b5e1375e67983ef7b5baa2511c680074fd31b00c/pymcts/tree.py#L78 -- here we need to use the fact that N
and Node
are identical.