Created
August 9, 2020 11:50
-
-
Save jaycosaur/4aa80cd1ae8b59a8543dd0adcab61f30 to your computer and use it in GitHub Desktop.
Composable types [python-protocol] - Typescript to Python field guide
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
from typing import Protocol | |
class Animal(Protocol): | |
length: float | |
def eat(self, food: str) -> None: | |
... | |
# Fish extends the protocol Animal and is itself a protocol | |
class Fish(Animal, Protocol): | |
def swim(self, how_long: float) -> None: | |
... | |
# MyFish implements the Fish interface implicitly without inheritance | |
class MyFish: | |
length: float = 12 | |
def eat(self, food: str) -> None: | |
print(f"Eating {food}") | |
def swim(self, howLong: float) -> None: | |
print(f"Swimming for {howLong}") | |
# MyFish implements the Fish protocol but does not directly reference it | |
fish = MyFish() | |
def do_something_fishy(what: Fish): | |
what.eat("worms") | |
what.swim(what.length) | |
do_something_fishy(fish) # this is ok! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment