Cached Property

2.0.1 · active · verified Sun Mar 29

cached-property (current version 2.0.1) is a Python decorator for caching the results of properties in classes. It provides a straightforward way to memoize expensive computations, executing them only once per instance and storing the result as a regular attribute. The library offers basic, thread-safe, and time-based (TTL) caching mechanisms, as well as experimental async/await compatibility. It maintains an active development status with releases typically aligned with Python version support updates.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `cached_property` decorator to cache an expensive property computation. The `boardwalk` property will only execute its logic once per instance, returning the cached value on subsequent accesses until explicitly invalidated.

from cached_property import cached_property

class Monopoly:
    def __init__(self):
        self.boardwalk_price = 500

    @cached_property
    def boardwalk(self):
        # In reality, this might represent a database call or time
        # intensive task like calling a third-party API.
        self.boardwalk_price += 50
        return self.boardwalk_price

monopoly = Monopoly()
print(f"First access: {monopoly.boardwalk}")
print(f"Second access (cached): {monopoly.boardwalk}")

# To invalidate the cache, delete the attribute:
del monopoly.__dict__['boardwalk'] # Or del monopoly.boardwalk for simple cases
print(f"After invalidation: {monopoly.boardwalk}")

view raw JSON →