From 7594c37236a364264bf52d2d18aceb974068c675 Mon Sep 17 00:00:00 2001 From: Maximilien Cuony Date: Thu, 27 Feb 2025 11:35:30 +0100 Subject: [PATCH] Change __getattribute__ to raise AttributeErrors instead of KeyErrors --- src/implicitdict/__init__.py | 7 +++++-- tests/test_normal_usage.py | 2 +- tests/test_optional.py | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/implicitdict/__init__.py b/src/implicitdict/__init__.py index a43d575..719ec4d 100644 --- a/src/implicitdict/__init__.py +++ b/src/implicitdict/__init__.py @@ -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): @@ -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: diff --git a/tests/test_normal_usage.py b/tests/test_normal_usage.py index b6a0f29..dce8a75 100644 --- a/tests/test_normal_usage.py +++ b/tests/test_normal_usage.py @@ -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) diff --git a/tests/test_optional.py b/tests/test_optional.py index 53663aa..087a60d 100644 --- a/tests/test_optional.py +++ b/tests/test_optional.py @@ -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 `"" in ` (see above). assert data.optional_field1 == None