Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions guardrails/classes/generic/serializeable.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,14 @@ class Serializeable:
@classmethod
def from_dict(cls, data: Dict[str, Any]):
annotations = get_annotations(cls)
attributes = dict.keys(annotations)
snake_case_kwargs = {
snake_case(k): data.get(k) for k in data if snake_case(k) in attributes
}
snake_case_kwargs["encoder"] = snake_case_kwargs.get(
"encoder", SerializeableJSONEncoder
)
# Convert the keys of annotations dict to a set for faster lookup
attributes = set(annotations)
# Precompute snake_case for each input key, avoid repeated computation in the comprehension
sc_data = {snake_case(k): v for k, v in data.items()}
# Only keep those that are present in attributes
snake_case_kwargs = {k: v for k, v in sc_data.items() if k in attributes}
# Use setdefault to avoid recomputing key and ensure compatible default
snake_case_kwargs.setdefault("encoder", SerializeableJSONEncoder)
return cls(**snake_case_kwargs) # type: ignore

@property
Expand Down