Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active October 4, 2020 09:51
Show Gist options
  • Save gidgid/9d6bc7a9836a12aaf039136a2d64fae4 to your computer and use it in GitHub Desktop.
Save gidgid/9d6bc7a9836a12aaf039136a2d64fae4 to your computer and use it in GitHub Desktop.
validate_assignment fixes setter type coercion problem
import pytest
from pydantic import BaseModel, ValidationError
class Pizza(BaseModel):
toppings_count: int
size: str
class Config: # 1
validate_assignment = True # 2
def test_pydantic_allows_setters_conversions():
pizza = Pizza(toppings_count='4', size='XL')
assert pizza.toppings_count == 4
pizza.toppings_count = '5' # 3
assert pizza.toppings_count == 5 # 3
with pytest.raises(ValidationError): # 4
pizza.toppings_count = 'no conversion' # 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment