python-attrs / python-attrs/attrs

cached_property in slotted classes doesn't work if overridden in child class

Open
#1,333 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

With attrs 24.2.0 and 23.2.0, if you use cached_property and try to override it in a child, and access the parent value, you get an AttributeError. We ran into this in our code when converting some classes to use slots.

I see there was support added in 24.2.0 for

Allow super() calls in slotted cached properties

But attrs still doesn't support "super() calls of overridden cached_property's in slotted classes":

from functools import cached_property
import attrs

@attrs.define(slots=True)
class Parent:
    @cached_property
    def name(self) -> str:
        return "Alice"

@attrs.define(slots=True)
class Child(Parent):
    @cached_property
    def name(self) -> str:
        return f"Bob (son of {super().name})"

p = Parent()
print(p.name)  # prints Alice
c = Child()
print(c.name)  # error:
Traceback (most recent call last):
  File "foo.py", line 23, in <module>
    print(c.name)
          ^^^^^^
  File "<attrs generated getattr __main__.Child>", line 6, in __getattr__
  File "foo.py", line 18, in name
    return f"Bob (son of {super().name})"
                          ^^^^^^^^^^^^
AttributeError: 'Child' object has no attribute 'name'

Workarounds:

  • disable slots
  • don't use cached_property
  • don't override the method

Elaboration:

I see the special handling is described in the docs and I see in the code that it generates a special __getattr__ that sets the generated value in the slot after being called. Perhaps when constructing a class, attrs should also walk the MRO for cached_propertys and handle any overridden cached_property methods — perhaps create some sort of namespaced/name-mangled properties for the parent.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/attr/_make.py around the generated getattr handling described in the issue, and read the cached-properties-on-slotted-classes documentation. Run the provided Parent/Child reproducer and trace the generated lookup across the MRO. Done means Child().name can call the parent cached_property and produce "Bob (son of Alice)" without disabling slots.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.