Skip to content

Commit df655ca

Browse files
committed
Use class matches in resource.update()
This was introduced in 3.10, and seems like a much better way to handle matching a type. Signed-off-by: Nic Cope <[email protected]>
1 parent 5fe3b5c commit df655ca

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

crossplane/function/resource.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,18 @@ def update(r: fnv1.Resource, source: dict | structpb.Struct | pydantic.BaseModel
3636
3737
The source can be a dictionary, a protobuf Struct, or a Pydantic model.
3838
"""
39-
# If the resource has a model_dump attribute it's a Pydantic BaseModel.
40-
if hasattr(source, "model_dump"):
41-
r.resource.update(source.model_dump(exclude_defaults=True, warnings=False))
42-
return
43-
44-
# If the resource has a get_or_create_struct attribute it's a Struct.
45-
if hasattr(source, "get_or_create_struct"):
46-
# TODO(negz): Use struct_to_dict and update to match other semantics?
47-
r.resource.MergeFrom(source)
48-
return
49-
50-
# If it has neither, it must be a dictionary.
51-
r.resource.update(source)
52-
return
39+
match source:
40+
case pydantic.BaseModel():
41+
r.resource.update(source.model_dump(exclude_defaults=True, warnings=False))
42+
case structpb.Struct():
43+
# TODO(negz): Use struct_to_dict and update to match other semantics?
44+
r.resource.MergeFrom(source)
45+
case dict():
46+
r.resource.update(source)
47+
case _:
48+
t = type(source)
49+
msg = f"Unsupported type: {t}"
50+
raise TypeError(msg)
5351

5452

5553
def dict_to_struct(d: dict) -> structpb.Struct:

0 commit comments

Comments
 (0)