Skip to content

Instantly share code, notes, and snippets.

@jaycosaur
Created August 9, 2020 11:50
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 jaycosaur/4aa80cd1ae8b59a8543dd0adcab61f30 to your computer and use it in GitHub Desktop.
Save jaycosaur/4aa80cd1ae8b59a8543dd0adcab61f30 to your computer and use it in GitHub Desktop.
Composable types [python-protocol] - Typescript to Python field guide
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