Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active October 2, 2020 11:46
Show Gist options
  • Save gidgid/fa25db2632e00a9c447f29b218ccaf8c to your computer and use it in GitHub Desktop.
Save gidgid/fa25db2632e00a9c447f29b218ccaf8c to your computer and use it in GitHub Desktop.
Using validate_assignment to enforce type coercion
import pytest
from pydantic import BaseModel, ValidationError
class StrictPizza(BaseModel):
toppings_count: int
size: str
class Config:
validate_assignment = True # enforces coercion
def test_pydantic_allows_setters_conversions():
pizza = StrictPizza(toppings_count='4', size='XL')
assert pizza.toppings_count == 4
pizza.toppings_count = '5'
assert pizza.toppings_count == 5
with pytest.raises(ValidationError):
pizza.toppings_count = 'no coercion'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment