Created
March 15, 2023 19:01
-
-
Save zhukovgreen/f3da32804a6258067b00b2ef6768c9d1 to your computer and use it in GitHub Desktop.
Example of typeclasses in python
This file contains 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
import sys | |
import typing | |
import classes | |
Paper = typing.NewType("Paper", str) | |
# RecycledPaper = typing.NewType("RecycledPaper", str) | |
# typeclasses works with real types, protocols and generics only | |
class RecycledPaper(str): | |
... | |
@typing.runtime_checkable | |
class SupportConvertToPaper(typing.Protocol): | |
def convert_to_paper(self) -> Paper: | |
... | |
class Wood: | |
def convert_to_paper(self) -> Paper: | |
return Paper("converted from Wood") | |
@classes.typeclass | |
def paper_factory(material) -> Paper: | |
... | |
@paper_factory.instance(protocol=SupportConvertToPaper) | |
def _paper_factory(material: SupportConvertToPaper) -> Paper: | |
return material.convert_to_paper() | |
# @paper_factory.instance(RecycledPaper) | |
# def _paper_factory(material: RecycledPaper) -> Paper: | |
# return RecycledPaper("converted from recycled paper") | |
@paper_factory.instance(RecycledPaper) | |
def _paper_factory(material: RecycledPaper) -> Paper: | |
return RecycledPaper("converted from recycled paper") | |
def test_impl(): | |
print(paper_factory(Wood()), file=sys.stderr) | |
# print(paper_factory(RecycledPaper(""))) | |
print(paper_factory(RecycledPaper("")), file=sys.stderr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment