ch15: draft examples

This commit is contained in:
Luciano Ramalho
2021-05-20 22:58:05 -03:00
parent 5312d4f824
commit 1689eec623
19 changed files with 501 additions and 36 deletions

View File

@@ -0,0 +1,47 @@
from typing import TypeVar, Generic, Any
class Pet:
"""Domestic animal kept for companionship."""
class Dog(Pet):
"""Canis familiaris"""
class Cat(Pet):
"""Felis catus"""
class Siamese(Cat):
"""Cat breed from Thailand"""
T = TypeVar('T')
class Box(Generic[T]):
def put(self, item: T) -> None:
self.contents = item
def get(self) -> T:
return self.contents
T_contra = TypeVar('T_contra', contravariant=True)
class InBox(Generic[T_contra]):
def put(self, item: T) -> None:
self.contents = item
T_co = TypeVar('T_co', covariant=True)
class OutBox(Generic[T_co]):
def __init__(self, contents: Any):
self.contents = contents
def get(self) -> Any:
return self.contents

View File

@@ -0,0 +1,42 @@
from typing import TYPE_CHECKING
from petbox import *
cat_box: Box[Cat] = Box()
si = Siamese()
cat_box.put(si)
animal = cat_box.get()
#if TYPE_CHECKING:
# reveal_type(animal) # Revealed: petbox.Cat*
################### Covariance
out_box: OutBox[Cat] = OutBox(Cat())
out_box_si: OutBox[Siamese] = OutBox(Siamese())
## Incompatible types in assignment
## expression has type "OutBox[Cat]"
# variable has type "OutBox[Siamese]"
# out_box_si = out_box
out_box = out_box_si
################### Contravariance
in_box: InBox[Cat] = InBox()
in_box_si: InBox[Siamese] = InBox()
in_box_si = in_box
## Incompatible types in assignment
## expression has type "InBox[Siamese]"
## variable has type "InBox[Cat]"
# in_box = in_box_si