<@ULVA73B9P>, is there a way to define a flow run'...
# ask-community
j
@Marvin, is there a way to define a flow run's tags dynamically from within the flow code?
m
Yes, in Prefect 3.x, you can dynamically define a flow run's tags using the
tags
context manager. Here's a basic example:
Copy code
python
from prefect import flow, tags

@flow
def my_flow():
    print("Flow is running with dynamic tags!")

if __name__ == "__main__":
    dynamic_tag = "dynamic_tag_example"
    with tags(dynamic_tag):
        my_flow()
This code snippet demonstrates how to set a tag dynamically within the flow code. You can replace
"dynamic_tag_example"
with any logic to determine your tag name. For more context, you can refer to this example on GitHub.
j
But I want to do it from within the flow method itself, not the method calling the flow
k
Copy code
from prefect import flow, get_client
from prefect.runtime import flow_run

def update_tags(tags: list[str]):
    flow_run_id = flow_run.get_id()
    with get_client(sync_client=True) as client:
        client.update_flow_run(flow_run_id=flow_run_id, tags=tags)

@flow
def dynamic_tags_flow(thing: str):
    update_tags(["tag", "another_tag"])
    # additional logic


if __name__ == "__main__":
    dynamic_tags_flow("hi")
j
That did it, thanks @Kevin Grismore!
🙌 2
s
Thanks a lot @Kevin Grismore, finally found this solution here after searching for the whole internet. Can you let me know how to add dynamic tags for the task, because this doesn't work for tasks? Also, how to set different dynamic tags for different flow within a same script, or a subflow within a flow. I want to have different dynamic tags to each subflow. Thank you so much in advance for this help.
Can anyone help me on this, please?