Skip to content

refactor(validation): enforce exactly-one-set constraint on model fields in class types.Part #682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
18 changes: 18 additions & 0 deletions google/genai/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,24 @@ def from_code_execution_result(
code_execution_result = CodeExecutionResult(outcome=outcome, output=output)
return cls(code_execution_result=code_execution_result)

@pydantic.model_validator(mode='after')
def check_exactly_one_field_set(self) -> 'Part':
"""
Validates that exactly one of the optional fields is set.
"""
# Get all fields defined in this model (excluding potential private attributes)
# In Pydantic V2, self.model_fields gives the definitions
# We need the actual values, which are instance attributes
field_names = self.model_fields.keys()

# Count how many fields are set (not None)
set_fields_count = sum(1 for field_name in field_names if getattr(self, field_name) is not None)

# Check if the count is exactly 1
if set_fields_count != 1:
raise ValueError(f"Exactly one of the fields {list(field_names)} must be set. Found {set_fields_count} set.")

return self

class PartDict(TypedDict, total=False):
"""A datatype containing media content.
Expand Down