Created
September 10, 2025 20:02
-
-
Save phillipuniverse/335b4be0e053e0d94ccf702cd9ed1c9c to your computer and use it in GitHub Desktop.
Some testing between Pydantic v1 and v2
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
""" | |
The below tests the Pydantic 'extra' behavior between v1 and v2 | |
We can see that 'extra' does indeed behave the same between v1 and v2 | |
""" | |
import pydantic as pydantic_v2 | |
import pydantic.v1 | |
from pydantic import ConfigDict | |
class V1TestModel(pydantic.v1.BaseModel): | |
class Config: | |
extra = "allow" | |
field1: str | |
assert V1TestModel(field1="a", field2="b").dict() == {"field1": "a", "field2": "b"} | |
assert V1TestModel(field1="a", field2="b").json() == '{"field1": "a", "field2": "b"}' | |
class V2TestModel(pydantic_v2.BaseModel): | |
model_config = ConfigDict(extra="allow") | |
field1: str | |
v2_model = V2TestModel(field1="a", field2="b") | |
assert v2_model.dict() == {"field1": "a", "field2": "b"} # this is the deprecated way | |
assert v2_model.model_dump() == {"field1": "a", "field2": "b"} # this is the new way | |
assert v2_model.__pydantic_extra__ == {"field2": "b"} # new for v2 | |
assert v2_model.model_dump_json() == '{"field1":"a","field2":"b"}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment