Skip to content

Commit cf3ddfc

Browse files
authored
fix: prevent AttributeError when schema_dump receives None values (#530)
has_dict_attribute() was incorrectly returning True for None due to protocol checking behavior, causing schema_dump(None) to fail with AttributeError when trying to access None.__dict__. This affected nullable database fields using StoredObject types during JSON serialization. The fix adds an explicit None check before the protocol isinstance check. - Add explicit None check to has_dict_attribute() - Add test case verifying None values are handled correctly
1 parent 4698506 commit cf3ddfc

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

advanced_alchemy/service/typing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,8 @@ def has_dict_attribute(obj: Any) -> "TypeGuard[DictProtocol]":
259259
Returns:
260260
bool
261261
"""
262-
263-
return isinstance(obj, DictProtocol)
262+
# Protocol checking returns True for None, so add explicit check
263+
return obj is not None and isinstance(obj, DictProtocol)
264264

265265

266266
def is_row_mapping(v: Any) -> TypeGuard["RowMapping"]:

tests/unit/test_attrs_integration.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,17 @@ def test_schema_dump_non_attrs_unchanged(self) -> None:
230230
dict_data = {"name": "test", "age": 30}
231231
assert schema_dump(dict_data) == dict_data
232232

233+
def test_schema_dump_none_value(self) -> None:
234+
"""Test that schema_dump correctly handles None values.
235+
236+
schema_dump should gracefully handle None input values without raising
237+
AttributeError, returning None as-is through the fallback mechanism.
238+
This is important for nullable database fields that may contain None.
239+
"""
240+
# schema_dump should handle None without raising AttributeError
241+
result = schema_dump(None)
242+
assert result is None
243+
233244
@pytest.mark.skipif(not ATTRS_INSTALLED, reason="attrs not installed")
234245
def test_schema_dump_exclude_unset_parameter(self) -> None:
235246
"""Test schema_dump exclude_unset parameter (attrs always includes all fields)."""

0 commit comments

Comments
 (0)