Skip to content

Commit

Permalink
Change __getattribute__ to raise AttributeErrors instead of KeyErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
the-glu committed Feb 27, 2025
1 parent a137d9e commit 7594c37
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
7 changes: 5 additions & 2 deletions src/implicitdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,10 @@ def __getattribute__(self, item):
self_type_name = _fullname(self_type)
if self_type_name in fields_info_by_type:
if item in fields_info_by_type[self_type_name].all_fields:
return self[item]
try:
return self[item]
except KeyError:
raise AttributeError
return super(ImplicitDict, self).__getattribute__(item)

def __setattr__(self, key, value):
Expand All @@ -165,7 +168,7 @@ def __setattr__(self, key, value):
self[key] = value
return
else:
raise KeyError('Attribute "{}" is not defined for "{}" object'.format(key, type(self).__name__))
raise AttributeError('Attribute "{}" is not defined for "{}" object'.format(key, type(self).__name__))
super(ImplicitDict, self).__setattr__(key, value)

def has_field_with_value(self, field_name: str) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_normal_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_basic_usage():

# Optional fields that aren't specified simply don't exist
assert 'baz' not in data
with pytest.raises(KeyError):
with pytest.raises(AttributeError):
assert data.baz == 0

# Optional fields can be omitted (fields with defaults are optional)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_optional.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ def test_minimally_defined():
assert "field_with_default" in data
assert "optional_field2_with_none_default" in data
assert "optional_field3_with_default" in data
with pytest.raises(KeyError):
# Trying to reference the Optional field will result in a KeyError
with pytest.raises(AttributeError):
# Trying to reference the Optional field will result in a AttributeError
# To determine whether an Optional field is present, the user must check
# whether `"<FIELD_NAME>" in <OBJECT>` (see above).
assert data.optional_field1 == None
Expand Down

0 comments on commit 7594c37

Please sign in to comment.