class cached_property: def __init__(self, func): self.func = func self.attrname = None self.__doc__ = func.__doc__ def __set_name__(self, owner, name): self.attrname = name def __get__(self, instance, owner): if instance is None: return self if self.attrname is None: raise AttributeError value = self.func(instance) instance.__dict__[self.attrname] = value return value
Decorators & Metaclasses

Meaning

A descriptor that caches the result of a method as an instance attribute after first access, returning the cached value on subsequent accesses.

Primary Function

Cache the result of a method call as an instance attribute to avoid recomputation.

Communicative Purpose

Indicate that a method's result should be cached and accessed like an attribute for efficiency.

Pattern

__get__ descriptor that caches the result in instance.__dict__ after first access.

Core Structure

__init__(self, func) stores func; __set_name__(self, owner, name) sets attrname; __get__(self, instance, owner) returns self if instance is None, raises AttributeError if attrname is None, otherwise computes value = func(instance), caches it in instance.__dict__[self.attrname] and returns it.

Função primária

Cache the result of a method call as an instance attribute to avoid recomputation.

Propósito comunicativo

Indicate that a method's result should be cached and accessed like an attribute for efficiency.

Situações de gatilho

When a method is expensive to compute, its return value does not change during the object's lifetime, and attribute‑like access is desired.

Contextos

Used in Python classes for expensive properties or methods that compute derived state, such as expensive computations, file I/O, or network calls that are idempotent for a given instance.

Padrão

__get__ descriptor that caches the result in instance.__dict__ after first access.

Estrutura central

__init__(self, func) stores func; __set_name__(self, owner, name) sets attrname; __get__(self, instance, owner) returns self if instance is None, raises AttributeError if attrname is None, otherwise computes value = func(instance), caches it in instance.__dict__[self.attrname] and returns it.

Slots de substituição

func: callable taking an instance; attrname: attribute name string; instance: object; owner: class.

Colocados típicos

  • property
  • functools.cached_property
  • descriptor
  • lazy property
  • memoization

Erros comuns

Applying to methods whose result can change (stale cache), forgetting to implement __set_name__ causing AttributeError, storing the cache in the class dict instead of the instance dict causing shared state

Similar / contraste

property (non‑caching), functools.cached_property (built‑in), lazy_property decorators, memoization decorators such as @lru_cache

Interferências

Using on methods that depend on mutable instance state can return outdated values; missing __set_name__ leads to AttributeError when attrname remains None.

Família do chunk

  • Python descriptors
  • properties
  • caching decorators

Nuance

The cached value replaces the descriptor in the instance's __dict__, making subsequent accesses simple attribute lookups without descriptor overhead.

Efeito pragmático

Signals that the attribute is expensive to compute but safe to treat as immutable for the instance’s lifetime.

Dica de memória

Think of a property that remembers its first computed value.

Nota

Equivalent to functools.cached_property introduced in Python 3.8; often used as a backport for older versions.

Upgrade path

Use functools.cached_property (Python 3.8+) or add a threading.Lock for thread‑safe caching

Tipo de construção: Descriptor protocol implementation with __init__, __set_name__, and __get__ methods.Tag de espaçamento: Medium-term

Log in to save chunks.