1. Helpers
  2. Cache

New to Gradio? Start here: Getting Started

See the Release History

To install Gradio from main, run the following command:

pip install https://gradio-builds.s3.amazonaws.com/15ce43720d1611f44e4661c74d604eabe0d04daf/gradio-6.28.0-py3-none-any.whl

*Note: Setting share=True in launch() will not work.

Cache

gradio.Cache(···)

Description

Thread-safe cache with manual get/set control, injected as a function parameter (add as a default parameter value and Gradio will inject it automatically). Supports per-session isolation so cached data doesn't leak between users, content-aware hashing for ML types (numpy, PIL, pandas), and LRU eviction with memory limits.

Example Usage

import gradio as gr

def generate(prompt, c=gr.Cache(per_session=True)):
    hit = c.get(prompt)
    if hit is not None:
        return hit["result"]
    result = llm(prompt)
    c.set(prompt, result=result)
    return result

Initialization

Parameters
🔗
max_size: int
default = 128
🔗
max_memory: str | int | None
default = None
🔗
per_session: bool
default = False

Methods

get

gradio.Cache.get(key, ···)

Description

Look up a cache entry by key. Returns a dict of stored data, or None on miss. Keys can be any type supported by gr.cache (strings, numbers, numpy arrays, PIL images, etc.).

Parameters
🔗
key: Any

The cache key to look up.

set

gradio.Cache.set(key, data, ···)

Description

Store arbitrary keyword data under a key.

Parameters
🔗
key: Any

The cache key.

🔗
data: Any

Arbitrary keyword arguments to store.

keys

gradio.Cache.keys(···)

Description

Return all stored raw keys. Useful for iteration or prefix matching.

clear

gradio.Cache.clear(···)

Description

Clear all entries from the cache.