|
| 1 | +from typing import Any, ClassVar |
| 2 | + |
1 | 3 | from pydantic import BaseModel, ConfigDict
|
| 4 | +from pydantic.alias_generators import to_camel |
| 5 | + |
| 6 | + |
| 7 | +def to_camel_custom(snake: str) -> str: |
| 8 | + """Convert a snake_case string to camelCase. |
| 9 | +
|
| 10 | + Args: |
| 11 | + snake: The string to convert. |
| 12 | +
|
| 13 | + Returns: |
| 14 | + The converted camelCase string. |
| 15 | + """ |
| 16 | + # First, remove any trailing underscores. This is common for names that |
| 17 | + # conflict with Python keywords, like 'in_' or 'from_'. |
| 18 | + if snake.endswith('_'): |
| 19 | + snake = snake.rstrip('_') |
| 20 | + return to_camel(snake) |
2 | 21 |
|
3 | 22 |
|
4 | 23 | class A2ABaseModel(BaseModel):
|
5 | 24 | """Base class for shared behavior across A2A data models.
|
6 | 25 |
|
7 | 26 | Provides a common configuration (e.g., alias-based population) and
|
8 | 27 | serves as the foundation for future extensions or shared utilities.
|
| 28 | +
|
| 29 | + This implementation provides backward compatibility for camelCase aliases |
| 30 | + by lazy-loading an alias map upon first use. |
9 | 31 | """
|
10 | 32 |
|
11 | 33 | model_config = ConfigDict(
|
12 | 34 | # SEE: https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.populate_by_name
|
13 | 35 | validate_by_name=True,
|
14 | 36 | validate_by_alias=True,
|
| 37 | + serialize_by_alias=True, |
| 38 | + alias_generator=to_camel_custom, |
15 | 39 | )
|
| 40 | + |
| 41 | + # Cache for the alias -> field_name mapping. |
| 42 | + # It starts as None and is populated on first access. |
| 43 | + _alias_to_field_name_map: ClassVar[dict[str, str] | None] = None |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def _get_alias_map(cls) -> dict[str, str]: |
| 47 | + """Lazily builds and returns the alias-to-field-name mapping for the class. |
| 48 | +
|
| 49 | + The map is cached on the class object to avoid re-computation. |
| 50 | + """ |
| 51 | + if cls._alias_to_field_name_map is None: |
| 52 | + cls._alias_to_field_name_map = { |
| 53 | + field.alias: field_name |
| 54 | + for field_name, field in cls.model_fields.items() |
| 55 | + if field.alias is not None |
| 56 | + } |
| 57 | + return cls._alias_to_field_name_map |
| 58 | + |
| 59 | + def __setattr__(self, name: str, value: Any) -> None: |
| 60 | + """Allow setting attributes via their camelCase alias.""" |
| 61 | + # Get the map and find the corresponding snake_case field name. |
| 62 | + field_name = type(self)._get_alias_map().get(name) # noqa: SLF001 |
| 63 | + # If an alias was used, field_name will be set; otherwise, use the original name. |
| 64 | + super().__setattr__(field_name or name, value) |
| 65 | + |
| 66 | + def __getattr__(self, name: str) -> Any: |
| 67 | + """Allow getting attributes via their camelCase alias.""" |
| 68 | + # Get the map and find the corresponding snake_case field name. |
| 69 | + field_name = type(self)._get_alias_map().get(name) # noqa: SLF001 |
| 70 | + if field_name: |
| 71 | + # If an alias was used, retrieve the actual snake_case attribute. |
| 72 | + return getattr(self, field_name) |
| 73 | + |
| 74 | + # If it's not a known alias, it's a genuine missing attribute. |
| 75 | + raise AttributeError( |
| 76 | + f"'{type(self).__name__}' object has no attribute '{name}'" |
| 77 | + ) |
0 commit comments