Last active
September 11, 2019 06:40
-
-
Save sbliven/8fb593f005eeafc0fecef71063f5dc39 to your computer and use it in GitHub Desktop.
Test a difficult typing case. Python type annotations!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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