|
| 1 | +import warnings |
| 2 | + |
1 | 3 | from typing import Any, ClassVar |
2 | 4 |
|
3 | 5 | from pydantic import BaseModel, ConfigDict |
@@ -27,7 +29,8 @@ class A2ABaseModel(BaseModel): |
27 | 29 | serves as the foundation for future extensions or shared utilities. |
28 | 30 |
|
29 | 31 | This implementation provides backward compatibility for camelCase aliases |
30 | | - by lazy-loading an alias map upon first use. |
| 32 | + by lazy-loading an alias map upon first use. Accessing or setting |
| 33 | + attributes via their camelCase alias will raise a DeprecationWarning. |
31 | 34 | """ |
32 | 35 |
|
33 | 36 | model_config = ConfigDict( |
@@ -60,14 +63,37 @@ def __setattr__(self, name: str, value: Any) -> None: |
60 | 63 | """Allow setting attributes via their camelCase alias.""" |
61 | 64 | # Get the map and find the corresponding snake_case field name. |
62 | 65 | field_name = type(self)._get_alias_map().get(name) # noqa: SLF001 |
| 66 | + |
| 67 | + if field_name: |
| 68 | + # An alias was used, issue a warning. |
| 69 | + warnings.warn( |
| 70 | + ( |
| 71 | + f"Setting field '{name}' via its camelCase alias is deprecated and will be removed in version 0.3.0 " |
| 72 | + f"Use the snake_case name '{field_name}' instead." |
| 73 | + ), |
| 74 | + DeprecationWarning, |
| 75 | + stacklevel=2, |
| 76 | + ) |
| 77 | + |
63 | 78 | # If an alias was used, field_name will be set; otherwise, use the original name. |
64 | 79 | super().__setattr__(field_name or name, value) |
65 | 80 |
|
66 | 81 | def __getattr__(self, name: str) -> Any: |
67 | 82 | """Allow getting attributes via their camelCase alias.""" |
68 | 83 | # Get the map and find the corresponding snake_case field name. |
69 | 84 | field_name = type(self)._get_alias_map().get(name) # noqa: SLF001 |
| 85 | + |
70 | 86 | if field_name: |
| 87 | + # An alias was used, issue a warning. |
| 88 | + warnings.warn( |
| 89 | + ( |
| 90 | + f"Accessing field '{name}' via its camelCase alias is deprecated and will be removed in version 0.3.0 " |
| 91 | + f"Use the snake_case name '{field_name}' instead." |
| 92 | + ), |
| 93 | + DeprecationWarning, |
| 94 | + stacklevel=2, |
| 95 | + ) |
| 96 | + |
71 | 97 | # If an alias was used, retrieve the actual snake_case attribute. |
72 | 98 | return getattr(self, field_name) |
73 | 99 |
|
|
0 commit comments