@@ -160,6 +160,64 @@ def to_json(
160160 warnings = warnings ,
161161 )
162162
163+ def get (self , key : str , default : Any = None ) -> Any :
164+ """Get the value of an attribute by name, with an optional default value.
165+
166+ This method allows you to access model attributes by their string name,
167+ similar to how dict.get() works.
168+
169+ Args:
170+ key: The name of the attribute to get
171+ default: The value to return if the attribute doesn't exist or is None.
172+ Defaults to None.
173+
174+ Returns:
175+ The value of the attribute if it exists, otherwise the default value.
176+
177+ Examples:
178+ >>> model = MyModel(name="test", age=25)
179+ >>> model.get("name") # Returns "test"
180+ >>> model.get("nonexistent") # Returns None
181+ >>> model.get("nonexistent", "default") # Returns "default"
182+ """
183+ try :
184+ value = getattr (self , key )
185+ return value if value is not None else default
186+ except AttributeError :
187+ return default
188+
189+ def __json__ (self ) -> dict [str , Any ]:
190+ """Custom JSON serialization method.
191+
192+ This method is called by JSON encoders that support the __json__ protocol,
193+ making BaseModel objects directly serializable without requiring model_dump().
194+
195+ Returns:
196+ A dictionary representation of the model suitable for JSON serialization.
197+ """
198+ return self .model_dump (by_alias = True , exclude_unset = True )
199+
200+ def __reduce_ex__ (self , protocol ):
201+ """Support for pickle serialization by returning the dict representation."""
202+ return (self .__class__ .model_validate , (self .model_dump (by_alias = True , exclude_unset = True ),))
203+
204+ def __iter__ (self ):
205+ """Make BaseModel iterable to support dict() conversion."""
206+ data = self .model_dump (by_alias = True , exclude_unset = True )
207+ return iter (data .items ())
208+
209+ def keys (self ):
210+ """Return keys for dict-like interface."""
211+ return self .model_dump (by_alias = True , exclude_unset = True ).keys ()
212+
213+ def values (self ):
214+ """Return values for dict-like interface."""
215+ return self .model_dump (by_alias = True , exclude_unset = True ).values ()
216+
217+ def items (self ):
218+ """Return items for dict-like interface."""
219+ return self .model_dump (by_alias = True , exclude_unset = True ).items ()
220+
163221 @override
164222 def __str__ (self ) -> str :
165223 # mypy complains about an invalid self arg
0 commit comments