On this page
  1. functools.cached_property
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

functools.cached_property

Prev: functools.cache | Up: functools | Next: functools.cmp_to_key
Rel: functools.cache, functools.cmp_to_key, functools.lru_cache, functools.partial
Ref: docs.python.org — functools.cached_property
Tags: #public #python3 #stdlib #functools


Import

import functools
from functools import cached_property

Signature & Overview

functools.cached_property(func)

functools.cached_property class.

Usage

from functools import cached_property

class Report:
    def __init__(self, values: list[int]) -> None:
        self.values = values
        self.computations = 0

    @cached_property
    def total(self) -> int:
        self.computations += 1
        return sum(self.values)

r = Report([10, 20, 30])
assert r.total == 60 and r.total == 60 and r.computations == 1

Gotchas

REPL Inspect

from functools import cached_property
help(cached_property)

Linked from

Related notes