<@ULVA73B9P> how can I use value of task_run_name ...
# marvin-ai
d
@Marvin how can I use value of task_run_name parameter in the task?
m
thought for 372.3 seconds
Great question. In Prefect 3.x, you can read the actual task run name from the running task using the run context or the runtime helpers. Two easy options: 1) Use the run context (recommended) - Works anywhere inside a running task - Gives you access to the full task_run object (id, name, etc.)
Copy code
from prefect import task, get_run_logger
from prefect.context import get_run_context

@task(task_run_name="process-{i}")
def my_task(i: int):
    ctx = get_run_context()              # This is a TaskRunContext in a task
    logger = get_run_logger()
    <http://logger.info|logger.info>(f"My task run name is: {ctx.task_run.name}")
    return ctx.task_run.name
2) Use the runtime accessor - A concise, convenience accessor for the current task run
Copy code
from prefect import task
from prefect.runtime import task_run

@task
def my_task():
    current_name = task_run.name
    # or, in some environments, task_run.name.get()
    return current_name
How task_run_name is set - You can pass a template string that uses your task’s parameter names:
Copy code
@task(task_run_name="load-{table}-{partition}")
def load(table: str, partition: str): ...
- Or pass a callable that receives the parameters dict:
Copy code
@task(task_run_name=lambda params: f"load-{params['table']}-{params['partition']}")
def load(table: str, partition: str): ...
Helpful docs: - Run context: get_run_context - Runtime accessors (task run): prefect.runtime.task_run - Task options and run names: Task run names If you share a small snippet of your task, I can show exactly where to grab and use the run name.