Consider the following nested-tuple type Prop
and a pydantic
model using it:
<code>Prop = tuple[tuple[str, str], ...]
class MyModel(BaseModel):
prop: dict[Prop, list[float]]
</code>
<code>Prop = tuple[tuple[str, str], ...]
class MyModel(BaseModel):
prop: dict[Prop, list[float]]
</code>
Prop = tuple[tuple[str, str], ...]
class MyModel(BaseModel):
prop: dict[Prop, list[float]]
Serializing the model works just fine:
<code>dumped = MyModel(prop={(("a", "A"), ("b", "V")): [0.0, 1.1]}).model_dump(
mode="json"
)
# returns {'prop': {'a,A,b,V': [0.0, 1.1]}}
</code>
<code>dumped = MyModel(prop={(("a", "A"), ("b", "V")): [0.0, 1.1]}).model_dump(
mode="json"
)
# returns {'prop': {'a,A,b,V': [0.0, 1.1]}}
</code>
dumped = MyModel(prop={(("a", "A"), ("b", "V")): [0.0, 1.1]}).model_dump(
mode="json"
)
# returns {'prop': {'a,A,b,V': [0.0, 1.1]}}
But if I load the dumped dictionary back in, I get a ValidationError:
<code>MyModel(**dumped)
# pydantic_core._pydantic_core.ValidationError: 1 validation error for MyModel prop.a,A,b,V.[key]
# Input should be a valid tuple [type=tuple_type, input_value='a,A,b,V', input_type=str]
</code>
<code>MyModel(**dumped)
# pydantic_core._pydantic_core.ValidationError: 1 validation error for MyModel prop.a,A,b,V.[key]
# Input should be a valid tuple [type=tuple_type, input_value='a,A,b,V', input_type=str]
</code>
MyModel(**dumped)
# pydantic_core._pydantic_core.ValidationError: 1 validation error for MyModel prop.a,A,b,V.[key]
# Input should be a valid tuple [type=tuple_type, input_value='a,A,b,V', input_type=str]
I expected the model_dump
to produce output that can be read back in, but this is not the case. Is there an easy work around?
mode="json"
is required to deal with dates. The Prop
type is used extensively throughout my application, so manually serializing/deserializing it or annotating it in every pydantic
model that uses it would be very annoying.