Caching

By default a @computed property runs once per request and is recomputed on the next one. When a value is expensive, a heavy query or calculation, you can cache the result across requests with Django's cache backend. Pick how widely it is shared with scope.

Caching scopes

scope controls how long a computed value is remembered:

Scope Lifetime Use Case
"request" (default) Within one request Avoid recalculation during template rendering
"instance" Across requests, per component instance Expensive per-user calculations
"global" Across requests, shared by everyone Same data for all users given the same inputs

"instance" and "global" use Django's cache backend.

Caching per instance

Use scope="instance" to cache across requests for a specific component instance:

from interlace import Component, computed

class ReportBuilder(Component):
    start_date: str = ""
    end_date: str = ""

    @computed(scope="instance", key=['start_date', 'end_date'], seconds=300)
    def performance_data(self):
        # Expensive calculation - cached for 5 minutes
        return calculate_kpis(self.start_date, self.end_date)

Key Parameter The key parameter lists property names that affect the cached value. When any key property changes, it's a cache miss and the value is recomputed.

A global, shared cache

Use scope="global" when the result is the same for everyone given the same inputs, so all users share a single cached value instead of one per instance:

from interlace import Component, computed

class DashboardStats(Component):
    day: str = ""

    @computed(scope="global", key=['day'], seconds=1800)
    def totals(self):
        # Shared across all users; recomputed per `day`, cached 30 minutes
        return DailyStats.objects.filter(date=self.day).aggregate(...)

Decorator parameters

Parameter Default Description
scope "request" "request", "instance", or "global" (see above)
key [] Property names to include in the cache key (instance/global)
seconds 3600 TTL for the instance/global scopes (1 hour default)

Clearing cache

Clear cached values programmatically:

class ReportBuilder(Component):
    @computed(scope="instance", key=['date_range'])
    def report_data(self):
        return generate_report(self.date_range)

    def refresh_report(self):
        # Clear specific property
        self.clear_computed('report_data')

    def refresh_all(self):
        # Clear all computed caches for this component
        self.clear_computed()

Automatic Cache Clear Within-request cache is cleared at the start of each request. Instance and global caches are cleared when you call clear_computed().

View this page as markdown - handy as context for your AI tools. Full index at /llms.txt.

Theme
Accent
Ink