Skip to content

Commit

Permalink
Change file formatter to support v1 and v2 pydantic constructors
Browse files Browse the repository at this point in the history
The pydantic models that use the v1 compatibility class work
fine with model_validate but there are some v1 models that do
not inherit from that and also some classes like ScarletModelData
that emulate the pydantic v1 methods but are not using pydantic.

Therefore we need to still check parse_obj.
  • Loading branch information
timj committed Aug 4, 2023
1 parent 0248938 commit cd4480f
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions python/lsst/daf/butler/formatters/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,12 @@ def _coerceBuiltinType(self, inMemoryDataset: Any, writeStorageClass: StorageCla
and type(inMemoryDataset).__module__ == "builtins"
):
# Try different ways of converting to the required type.
if hasattr(writeStorageClass.pytype, "model_validate"):
# This is for a Pydantic model.
inMemoryDataset = writeStorageClass.pytype.model_validate(inMemoryDataset)
elif isinstance(inMemoryDataset, dict):
# Pydantic v1 uses parse_obj and some non-pydantic classes
# use that convention. Pydantic v2 uses model_validate.
for method_name in ("model_validate", "parse_obj"):
if method := getattr(writeStorageClass.pytype, method_name, None):
return method(inMemoryDataset)
if isinstance(inMemoryDataset, dict):
if dataclasses.is_dataclass(writeStorageClass.pytype):
# Dataclasses accept key/value parameters.
inMemoryDataset = writeStorageClass.pytype(**inMemoryDataset)
Expand Down

0 comments on commit cd4480f

Please sign in to comment.