Skip to content

Commit

Permalink
Use class matches in resource.update()
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
negz committed Oct 10, 2024
1 parent 5fe3b5c commit df655ca
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions crossplane/function/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,18 @@ def update(r: fnv1.Resource, source: dict | structpb.Struct | pydantic.BaseModel
The source can be a dictionary, a protobuf Struct, or a Pydantic model.
"""
# If the resource has a model_dump attribute it's a Pydantic BaseModel.
if hasattr(source, "model_dump"):
r.resource.update(source.model_dump(exclude_defaults=True, warnings=False))
return

# If the resource has a get_or_create_struct attribute it's a Struct.
if hasattr(source, "get_or_create_struct"):
# TODO(negz): Use struct_to_dict and update to match other semantics?
r.resource.MergeFrom(source)
return

# If it has neither, it must be a dictionary.
r.resource.update(source)
return
match source:
case pydantic.BaseModel():
r.resource.update(source.model_dump(exclude_defaults=True, warnings=False))
case structpb.Struct():
# TODO(negz): Use struct_to_dict and update to match other semantics?
r.resource.MergeFrom(source)
case dict():
r.resource.update(source)
case _:
t = type(source)
msg = f"Unsupported type: {t}"
raise TypeError(msg)


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

0 comments on commit df655ca

Please sign in to comment.