<@ULVA73B9P> How do I get the flow name from withi...
# ask-marvin
d
@Marvin How do I get the flow name from within a task function?
m
thought for 206.8 seconds
Assuming Prefect 3.x, the simplest way is to use the runtime accessors. - Flow name (the flow object’s name):
prefect.runtime.flow_run.flow_name
- Flow run name (the specific run’s name):
prefect.runtime.flow_run.name
Example from inside a task:
Copy code
from prefect import flow, task, get_run_logger
from prefect.runtime import flow_run

@task
def show_names():
    logger = get_run_logger()
    <http://logger.info|logger.info>(f"Flow name: {flow_run.flow_name}")
    <http://logger.info|logger.info>(f"Flow run name: {flow_run.name}")

@flow
def my_flow():
    show_names()

if __name__ == "__main__":
    my_flow()
Alternative via the run context (less direct inside tasks):
Copy code
from prefect import task
from prefect.context import get_run_context
from prefect.runtime import flow_run

@task
def show_via_context():
    ctx = get_run_context()  # TaskRunContext in a task
    # Preferred: use the runtime accessor
    name = flow_run.flow_name
    # ctx also gives you task_run info (e.g., ctx.task_run.name), but not the flow name directly
Notes: -
prefect.runtime.flow_run.flow_name
is a property you read (not a function). - This works in Prefect 2.x as well; the runtime accessors are the most portable approach. - If you specifically need other runtime details, see Runtime context and Access runtime info.