Typing persistent data structure
I am trying to type check a persistent (immutable) data structure. However I am stumbling on restrictions on using covariant types as arguments. Is there a standard work around for this? Simplified Example: class Node(Generic[T_co]): def __init__(self, val: T_co, succ: Optional[Node[T_co]]) -> None: self.val: Final[T_co] = val self.succ: Final[Optional[Node[T_co]]] = succ class List(Sequence[T_co]): def __init__(self, *, _head: Optional[Node[T_co]] = None) -> None: self.head: Final[Optional[Node[T_co]]] = _head # The problem method def push_front(self, val: T_co) -> List[T_co]: new_node = Node(val, self.head) return List(_head=new_node) def __iter__(self) -> Iterator[T_co]: ptr = self.head while ptr is not None: yield ptr.val ptr = ptr.succ ...
What issues are you running into? I tried your example in the mypy
playground (
https://mypy-play.net/?mypy=latest&python=3.9&flags=verbose&gist=880f6fefd0d6a1b06af03a2c815ddfc3)
and got no errors related to T_co.
El mar, 16 mar 2021 a las 20:16, Caleb Donovick (
I am trying to type check a persistent (immutable) data structure. However I am stumbling on restrictions on using covariant types as arguments. Is there a standard work around for this?
Simplified Example:
class Node(Generic[T_co]): def __init__(self, val: T_co, succ: Optional[Node[T_co]]) -> None: self.val: Final[T_co] = val self.succ: Final[Optional[Node[T_co]]] = succ
class List(Sequence[T_co]): def __init__(self, *, _head: Optional[Node[T_co]] = None) -> None: self.head: Final[Optional[Node[T_co]]] = _head
# The problem method def push_front(self, val: T_co) -> List[T_co]: new_node = Node(val, self.head) return List(_head=new_node)
def __iter__(self) -> Iterator[T_co]: ptr = self.head while ptr is not None: yield ptr.val ptr = ptr.succ ...
_______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: jelle.zijlstra@gmail.com
participants (2)
-
Caleb Donovick
-
Jelle Zijlstra