Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active October 4, 2020 19:04
Show Gist options
  • Save gidgid/9f9ac44985600b0d33828f413e6f77c1 to your computer and use it in GitHub Desktop.
Save gidgid/9f9ac44985600b0d33828f413e6f77c1 to your computer and use it in GitHub Desktop.
Why is it useful to pass specialized models to functions
from pydantic import BaseModel
class Age(BaseModel):
__root__: int
def age_in_days(age: Age) -> int:
return age.__root__ * 365 # 1
def test_age_in_days_only_needs_to_deal_with_ints():
age = Age.parse_obj('42') # 2
assert age_in_days(age) == 42 * 365
# note that mypy raises an error when trying the following
# will raise a mypy error
# age_in_days(age='not an age') # 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment