<@ULVA73B9P> Can I access the parent flow attribut...
# ask-marvin
a
@Marvin Can I access the parent flow attributes of a sub flow, when inside the sub flow?
m
Accessing parent flow attributes from a subflow in Prefect 3.x isn't directly supported via a built-in mechanism. Subflows are treated as independent flows, and they don't inherently have access to their parent flow's context or attributes. However, you can pass necessary data explicitly from the parent flow to the subflow as parameters. This way, any attributes or context needed by the subflow can be provided directly. Here's a simple example of how you might achieve this:
Copy code
python
from prefect import flow

@flow
def parent_flow():
    parent_attribute = "some_value"
    sub_flow(parent_attribute)

@flow
def sub_flow(parent_attribute):
    print(f"Received from parent: {parent_attribute}")

if __name__ == "__main__":
    parent_flow()
In this example,
parent_attribute
is passed from the
parent_flow
to the
sub_flow
, allowing the subflow to utilize the data from its parent. For more details, you might want to explore the Prefect documentation or the Prefect GitHub repository.
a
@Marvin Can I get the parent flow ID when inside a subflow?
m
In Prefect 3.x, you can access the parent flow run ID from within a subflow using the
parent_task_run_id
attribute when creating a subflow run. This ID is associated with the task run that initiated the subflow. Here's a relevant excerpt from the Prefect source code:
Copy code
python
flow_run = client.create_flow_run(
    flow=self.flow,
    parameters=self.flow.serialize_parameters(parameters),
    state=Pending(),
    parent_task_run_id=getattr(parent_task_run, "id", None),
    tags=TagsContext.get().current_tags,
)
This snippet shows how the
parent_task_run_id
is set when creating a subflow run. However, to access this ID within the subflow, you would typically need to pass it explicitly as a parameter or use a context that retains this information. For more details, you might want to explore the Prefect documentation or the Prefect GitHub repository.