<@ULVA73B9P> How can I explicitly enable caching f...
# ask-marvin
c
@Marvin How can I explicitly enable caching for a specific task, if I have
PREFECT_TASKS_DEFAULT_NO_CACHE
set globally?
m
thought for 148.8 seconds
Assuming Prefect 3.x: when
PREFECT_TASKS_DEFAULT_NO_CACHE=true
, tasks default to
NO_CACHE
only if you don’t explicitly set caching on the task. To enable caching for a specific task, provide either a
cache_policy
or a
cache_key_fn
on that task. There’s no
no_cache=False
flag. Common options: - Use the default policy (recommended)
Copy code
from prefect import task
from prefect.cache_policies import DEFAULT

@task(cache_policy=DEFAULT)
def my_task(x):
    return x * 2
- Cache based on inputs only
Copy code
from prefect import task
from prefect.cache_policies import Inputs

@task(cache_policy=Inputs())
def my_task(x):
    return x * 2
- Custom cache key (optionally with expiration)
Copy code
from datetime import timedelta
from prefect import task
from prefect.tasks import task_input_hash

@task(cache_key_fn=task_input_hash, cache_expiration=timedelta(hours=1))
def my_task(x):
    return x * 2
- If you can’t edit the decorator, override with
with_options
Copy code
from prefect.cache_policies import DEFAULT

cached_task = my_task.with_options(cache_policy=DEFAULT)
Notes: -
cache_key_fn
takes precedence if both
cache_policy
and
cache_key_fn
are set. - Setting only
cache_expiration
does not enable caching; pair it with a
cache_policy
or
cache_key_fn
.