Last active
October 2, 2020 11:46
-
-
Save gidgid/fa25db2632e00a9c447f29b218ccaf8c to your computer and use it in GitHub Desktop.
Using validate_assignment to enforce type coercion
This file contains hidden or 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
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