Skip to content

Extend cached_property to let the user select the attribute name #141216

@clayote

Description

@clayote

Feature or enhancement

Proposal:

Use case

My program has a lot of objects that are nearly stateless of themselves, but which have properties that instantiate richer objects that may have lots of state, including arbitrary data provided by the user. I wanted to use @cached_property to keep most of the objects nice and light, and only allocate much memory when the user refers to those properties.

Problem

The objects in question have the __slots__ attribute. @cached_property doesn't work with that.

Solution

I have a pull request incoming to add behavior to @cached_property so that if it's called like

class Something:
    __slots__ = ("_spam",)

    @cached_property("_spam")
    def eggs(self):
        return {"ham": "delicious"}

beans = Something()
print(beans.eggs)

this will cache {"ham": "delicious"} in the "_spam" slot, but only at the very end, when we refer to beans.eggs.

This has the side effect that the eggs property can be assigned to other names. I don't need this, but I couldn't think of a reason to forbid it.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions