Skip to content

Instantly share code, notes, and snippets.

@sbliven
Last active September 11, 2019 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbliven/8fb593f005eeafc0fecef71063f5dc39 to your computer and use it in GitHub Desktop.
Save sbliven/8fb593f005eeafc0fecef71063f5dc39 to your computer and use it in GitHub Desktop.
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