Last active
June 18, 2019 08:58
-
-
Save wouterdb/d3bdc796ed2b3e55cfcc4656693cbbdb to your computer and use it in GitHub Desktop.
Pydantic Puzzlers
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 pydantic | |
class Project(pydantic.BaseModel): | |
source: str | |
validate_: bool = False | |
class Config: | |
# validate is not a valid field name, because BaseModel has a validate method | |
# use alias so we can use a validate field in the json and validate_ in python | |
fields = {"validate_": {"alias": "validate"}} | |
def roundtrip(project_in: Project) -> None: | |
"""Convert to json and back """ | |
project_out = Project(**project_in.dict()) | |
print(f"input: {project_in.validate_}, output: {project_out.validate_}") | |
projectt = Project(source="test", validate=True) | |
roundtrip(projectt) | |
projectf = Project(source="test", validate=False) | |
roundtrip(projectf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment