Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

functools.cached_property

Computes an attribute on first access and stores the result in the instance dictionary.

Version: Python 3.14; repository image, production runtime not attested

Syntax

@functools.cached_property

Computes an attribute on first access and stores the result in the instance dictionary.

Deleting the cached attribute makes the next access recompute it, so dependent state can change between computations.

On first lookup, compute a value and write it under the same name in the instance's mutable __dict__. Assignment overrides it and deletion enables recomputation. An instance without a writable dictionary cannot use this mechanism. Since 3.12 there is no built-in per-property lock, so races can compute it twice. The example returns 6, 6, then 10.

from functools import cached_property
class Sample:
    @cached_property
    def value(self):
        return object()
s = Sample()
v = s.value
assert s.value is v and s.__dict__["value"] is v
s.value = 4
assert s.value == 4
del s.value
assert s.value is not v

Examples

import functools
class Sample:
    value = 3
    @functools.cached_property
    def twice(self): return self.value * 2

s = Sample()
print(s.twice)
s.value = 5
print(s.twice)
del s.twice
print(s.twice)

Result

6
6
10

On first lookup, compute a value and write it under the same name in the instance's mutable `__dict__`. Assignment overrides it and deletion enables recomputation. An instance without a writable dictionary cannot use this mechanism. Since 3.12 there is no built-in per-property lock, so races can compute it twice. The example returns 6, 6, then 10.

Sources