Created
March 15, 2022 17:25
-
-
Save pmbrull/7ef7dba9ac74dce586aa635a081e5f06 to your computer and use it in GitHub Desktop.
How to make the most of Pydantic 07
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
from functools import singledispatch | |
@singledispatch | |
def process(model): | |
""" | |
Default processing definition | |
""" | |
raise NotImplementedError(f"I don't know how to process {type(model)}") | |
@process.register | |
def _(model: Address): | |
""" | |
Handle addresses | |
""" | |
print(f"Just got an address from {model.city}") | |
@process.register | |
def _(model: CatRequest): | |
""" | |
Handle Cat Requests | |
""" | |
print(f"Processing {model.name} the cat!") | |
address = Address( | |
city="Wonderland", | |
zip_code="ABCDE", | |
number=123, | |
) | |
cat = CatRequest( | |
name="Lévy", | |
age=3, | |
address=address | |
) | |
process(address) # Just got an address from Wonderland | |
process(cat) # Processing Lévy the cat! | |
process("something else") # NotImplementedError: I don't know how to process <class 'str'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment