Skip to content

docs: clarify using lru_cache on class method keeps a reference to the instance #96851

Closed
@codicocodes

Description

@codicocodes

Documentation

When using the lru_cache decorator on class methods the cached function keeps a reference to each instance (self) preventing the class instance from being garbage collected. This is expected behavior, as self is a parameter to the cached function. However, many use it on class methods expecting the cache to be on a per instance basis.

This video explains the issue in detail, and googling lru_cache memory leak gives a lot of examples of people who have faced this issue.

I suggest that we clarify this behavior in the documentation to prevent others from falling into this trap.

Perhaps modifying the following paragraph something like this:

The cache keeps references to the arguments and return values until they age out of the cache or until the cache is cleared. >>This includes references to self, which will prevent class instances from getting garbage collecting.<<

Would be happy to make a PR if you think this is a good idea.

Looking forward to feedback!

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions