Skip to content

Show how to clear a @functools.cached_property #135936

Open
@paulrougieux

Description

@paulrougieux

Documentation

While the current documentation for functools.cached_property mentions that “the cached value can be cleared by deleting the attribute,” it does not provide a concrete example of how to do this in practice. It may not be immediately obvious how to invalidate the cache. Adding this example would show how to handle the potential AttributeError if the property has not yet been accessed. It would also encourage idiomatic usage by showing the recommended way to clear a cached property, rather than directly manipulating the instance’s __dict__.

from functools import cached_property
import random

class Bicycle:
    @cached_property
    def seat_id(self):
        return random.randint(1000, 9999)

    def invalidate_cache(self):
        """Invalidate the cached seat_id property."""
        try:
            del self.seat_id
        except AttributeError:
            pass

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions