@Marvin, is there a way to define a flow run's tags dynamically from within the flow code?
m
Marvin
01/21/2025, 9:02 PM
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
Joe Blauer
01/21/2025, 9:03 PM
But I want to do it from within the flow method itself, not the method calling the flow
k
Kevin Grismore
01/21/2025, 9:04 PM
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
Joe Blauer
01/21/2025, 9:08 PM
That did it, thanks @Kevin Grismore!
🙌 2
s
Shahid Khan
02/06/2025, 4:51 AM
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.
Bring your towel and join one of the fastest growing data communities. Welcome to our second-generation open source orchestration platform, a completely rethought approach to dataflow automation.