Skip to content

Instantly share code, notes, and snippets.

@pmbrull
Created March 15, 2022 17:25
Show Gist options
  • Save pmbrull/7ef7dba9ac74dce586aa635a081e5f06 to your computer and use it in GitHub Desktop.
Save pmbrull/7ef7dba9ac74dce586aa635a081e5f06 to your computer and use it in GitHub Desktop.
How to make the most of Pydantic 07
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