Repository: python-attrs/attrs
Pull request #1253 (2024-03-05 15:18:49)

Preserve AttributeError in slotted classes with cached_property
# Summary

In slotted classes' generated `__getattr__()`, we try `__getattribute__()` before `__getattr__()`, if available, and eventually let `AttributeError` propagate. This matches better with the behaviour described in Python's documentation [Customizing attribute access](https://docs.python.org/3/reference/datamodel.html#customizing-attribute-access).

Fix https://github.com/python-attrs/attrs/issues/1230


# Pull Request Check List

- [x] Do **not** open pull requests from your `main` branch – **use a separate branch**!
  - There's a ton of footguns waiting if you don't heed this warning. You can still go back to your project, create a branch from your main branch, push it, and open the pull request from the new branch.
  - This is not a pre-requisite for your your pull request to be accepted, but **you have been warned**.
- [x] Added **tests** for changed code.
  Our CI fails if coverage is not 100%.
- [x] New features have been added to our [Hypothesis testing strategy](https://github.com/python-attrs/attrs/blob/main/tests/strategies.py).
- [x] Changes or additions to public APIs are reflected in our type stubs (files ending in ``.pyi``).
    - [x] ...and used in the stub test file `tests/typing_example.py`.
    - [x] If they've been added to `attr/__init__.pyi`, they've *also* been re-imported in `attrs/__init__.pyi`.
- [x] Updated **documentation** for changed code.
    - [x] New functions/classes have to be added to `docs/api.rst` by hand.
    - [x] Changes to the signature of `@attr.s()` have to be added by hand too.
    - [x] Changed/added classes/methods/functions have appropriate `versionadded`, `versionchanged`, or `deprecated` [directives](http://www.sphinx-doc.org/en/stable/markup/para.html#directive-versionadded).
          The next version is the second number in the current release + 1.
          The first number represents the current year.
          So if the current version on PyPI is 22.2.0, the next version is gonna be 22.3.0.
          If the next version is the first in the new year, it'll be 23.1.0.
- [x] Documentation in `.rst` and `.md` files is written using [semantic newlines](https://rhodesmill.org/brandon/2012/one-sentence-per-line/).
- [x] Changes (and possible deprecations) have news fragments in [`changelog.d`](https://github.com/python-attrs/attrs/blob/main/changelog.d).
- [x] Consider granting [push permissions to the PR branch](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork), so maintainers can fix minor issues themselves without pestering you.


hynek: ping @diabolo-dan :)

Patch:
diff --git a/changelog.d/1253.change.md b/changelog.d/1253.change.md
new file mode 100644
index 0000000..3c32d83
--- /dev/null
+++ b/changelog.d/1253.change.md
@@ -0,0 +1,1 @@
+Preserve `AttributeError` raised by properties of slotted classes with `functools.cached_properties`.
diff --git a/src/attr/_make.py b/src/attr/_make.py
index 0114582..d3bfb44 100644
--- a/src/attr/_make.py
+++ b/src/attr/_make.py
@@ -619,8 +619,12 @@ def _make_cached_property_getattr(cached_properties, original_getattr, cls):
     else:
         lines.extend(
             [
-                "         if hasattr(super(), '__getattr__'):",
-                "              return super().__getattr__(item)",
+                "         try:",
+                "             return super().__getattribute__(item)",
+                "         except AttributeError:",
+                "             if not hasattr(super(), '__getattr__'):",
+                "                 raise",
+                "             return super().__getattr__(item)",
                 "         original_error = f\"'{self.__class__.__name__}' object has no attribute '{item}'\"",
                 "         raise AttributeError(original_error)",
             ]


Test patch:
diff --git a/tests/test_slots.py b/tests/test_slots.py
index c1332f2..78215ea 100644
--- a/tests/test_slots.py
+++ b/tests/test_slots.py
@@ -806,6 +806,45 @@ def test_slots_cached_property_with_empty_getattr_raises_attribute_error_of_requ
         a.z
 
 
+@pytest.mark.skipif(not PY_3_8_PLUS, reason="cached_property is 3.8+")
+def test_slots_cached_property_raising_attributeerror():
+    """
+    Ensures AttributeError raised by a property is preserved by __getattr__()
+    implementation.
+
+    Regression test for issue https://github.com/python-attrs/attrs/issues/1230
+    """
+
+    @attr.s(slots=True)
+    class A:
+        x = attr.ib()
+
+        @functools.cached_property
+        def f(self):
+            return self.p
+
+        @property
+        def p(self):
+            raise AttributeError("I am a property")
+
+        @functools.cached_property
+        def g(self):
+            return self.q
+
+        @property
+        def q(self):
+            return 2
+
+    a = A(1)
+    with pytest.raises(AttributeError, match=r"^I am a property$"):
+        a.p
+    with pytest.raises(AttributeError, match=r"^I am a property$"):
+        a.f
+
+    assert a.g == 2
+    assert a.q == 2
+
+
 @pytest.mark.skipif(not PY_3_8_PLUS, reason="cached_property is 3.8+")
 def test_slots_cached_property_with_getattr_calls_getattr_for_missing_attributes():
     """