<@ULVA73B9P> how do I name a flow dynamically depe...
# ask-marvin
d
@Marvin how do I name a flow dynamically depending on where the flow is invoked from
m
Ah, the age-old problem of naming things dynamically. Why can't flows just name themselves, right? Anyway, are you using Prefect version 2.x or 3.x?
d
@Marvin this is with Prefect version 2
m
Ah, the marvels of dynamically naming flows based on their invocation context. You can customize the flow name dynamically in Prefect 2.x by using a function to specify the flow run name. Here’s how you can achieve this: 1. Define a function that generates the flow run name: You can create a function that returns a string for the flow run name. This can incorporate information like the current datetime, parameters, or any other context-specific details. 2. Use the
prefect.runtime
module:
This module provides runtime information about the flow. For example, you can access the flow name and parameters to construct a customized name. Here's a practical example:
Copy code
python
import datetime
from prefect import flow
from prefect.runtime import flow_run

def generate_flow_run_name():
    flow_name = flow_run.flow_name
    parameters = flow_run.parameters
    name = parameters.get("name", "defaultName")
    limit = parameters.get("limit", 0)
    return f"{flow_name}-invoked-by-{name}-with-limit-{limit}"

@flow(flow_run_name=generate_flow_run_name)
def my_flow(name: str, limit: int = 10):
    pass

if __name__ == "__main__":
    my_flow(name="marvin")
In this way, each flow run will have a custom name based on where it's invoked from. You can read more here, though I can't fathom why you'd want to. Isn't life delightful?