Skip to content

Instantly share code, notes, and snippets.

@sbliven sbliven/circular_types.py
Last active Sep 11, 2019

Embed
What would you like to do?
Test a difficult typing case. Python type annotations!
"""Test a difficult typing case.
Inspired by biopython's Bio.PDB.Entity.
https://gist.github.com/sbliven/8fb593f005eeafc0fecef71063f5dc39
"""
import sys
from typing import TypeVar, Union
if sys.version_info >= (3, 8):
from typing import Protocol
else:
from typing_extensions import Protocol
T = TypeVar("T")
ParentT = TypeVar("ParentT", bound="ParentOf", covariant=True)
ChildT = TypeVar("ChildT", bound="ChildOf", covariant=True)
Offspring = Union["Daughter", "Son"]
class ChildOf(Protocol[ParentT]):
def get_parent(self):
# type: () -> ParentT
pass
class ParentOf(Protocol[ChildT]):
def get_child(self):
# type: () -> ChildT
pass
class Mom(ParentOf[Offspring]):
def __init__(self, child):
# type: (Offspring) -> None
self.child = child # type: Offspring
def get_child(self):
# type: () -> Offspring
return self.child
class Daughter(ChildOf["Mom"]):
def __init__(self, parent):
# type: (Mom) -> None
self.parent = parent # type: Mom
def get_parent(self):
# type: () -> Mom
return self.parent
class Son(ChildOf["Mom"]):
def __init__(self, parent):
# type: (Mom) -> None
self.parent = parent # type: Mom
def get_parent(self):
# type: () -> Mom
return self.parent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.