<@ULVA73B9P> Investigate whether Flow Run runtime ...
# ask-marvin
u
@Marvin Investigate whether Flow Run runtime information and context can be used as template variables in the flow_run_name parameter of the Flow object.
m
thought for 134.3 seconds
Short answer: Yes—with some nuance. In Prefect 3.x: - If you pass a string to
flow_run_name
, only flow parameters are available as template variables via Python’s
str.format(...)
. - If you need other runtime details (run id, run count, scheduled start time, tags, etc.), pass a zero-argument callable. Inside that callable, read context from
prefect.runtime.flow_run
. What’s supported 1) String templates (parameters only) - Uses
str.format(**parameters)
with your flow’s parameters (including defaults). - Other runtime info (run id, start time, etc.) is NOT available in the string template. Example:
Copy code
from prefect import flow

@flow(flow_run_name="process-{dataset}-v{version}")
def analyze_data(dataset: str, version: int = 1):
    return f"Analyzed {dataset} v{version}"

analyze_data(dataset="sales")  # => flow run name: "process-sales-v1"
2) Callable (full runtime context) - Provide a zero-argument function that returns a string. - Access runtime details via `prefect.runtime.flow_run`: -
id
,
name
,
flow_name
,
flow_version
,
parameters
,
tags
,
run_count
,
scheduled_start_time
,
parent_flow_run_id
,
parent_deployment_id
,
root_flow_run_id
,
job_variables
,
api_url
,
ui_url
Examples:
Copy code
from prefect import flow
from prefect.runtime import flow_run as flow_run_ctx

def name_with_retry_and_id():
    return f"{flow_run_ctx.flow_name}-{flow_run_ctx.id[:8]}-attempt-{flow_run_ctx.run_count}"

@flow(flow_run_name=name_with_retry_and_id, retries=3)
def my_flow():
    pass
Copy code
from prefect import flow
from prefect.runtime import flow_run as flow_run_ctx

def env_aware_name():
    params = flow_run_ctx.parameters
    env = "prod" if params.get("is_production") else "dev"
    ts = flow_run_ctx.scheduled_start_time.strftime("%Y%m%d-%H%M%S") if flow_run_ctx.scheduled_start_time else "now"
    return f"{flow_run_ctx.flow_name}-{env}-{ts}"

@flow(flow_run_name=env_aware_name)
def deploy(is_production: bool = False):
    pass
When is it rendered? - The name is resolved after the flow run is created and the flow run context is established, but before your flow function body executes. It’s set once per run. Key notes - String templates: simple
{param}
placeholders only; no f-strings or runtime context. - Callables: must return a string; use
prefect.runtime.flow_run
for rich context. - Resolved once early in execution; UI will update from the initial name to your custom name. Helpful docs - Flows overview: Flows - Runtime context: Runtime - API reference for flow runtime context (module): prefect.runtime (see
flow_run
section) If you share a specific naming pattern you want (e.g., include param X, retry count, and a timestamp), I can sketch the exact
flow_run_name
function for it.