← retour aux snippets

functools: cached_property pour calculs coûteux

Mémoriser une propriété après le premier calcul (par instance).

python patterns #functools#cache

objectif

Mémoriser une propriété après le premier calcul (par instance).

code minimal

from functools import cached_property

class Repo:
    def __init__(self, url: str): self.url = url
    @cached_property
    def host(self): return self.url.split("/")[2]

r = Repo("https://data.pm/path")
print(r.host == "data.pm")  # attendu: True

utilisation

from functools import cached_property
class X:
    @cached_property
    def val(self): return 40 + 2
x = X()
print(x.val == 42)

variante(s) utile(s)

from functools import cached_property
class C:
    calls = 0
    @cached_property
    def heavy(self):
        C.calls += 1
        return 1
c = C(); _ = c.heavy; _ = c.heavy
print(C.calls == 1)

notes

  • Ne convient pas si l’état interne change; invalidez en supprimant l’attribut.
  • Disponible en stdlib (3.8+).