How can I stop a flow run execution based on a condition?

Prefect 2.0

To cancel a flow run based on some custom condition, you can raise an exception within your flow.

from prefect import task, flow
from random import random

def random_number():
    return random()

def short_circuit():
    while True:
        num = random_number().wait().result()
        if num > 0.5:
            raise ValueError("Big number!")

if __name__ == "__main__":

Prefect 1.0

You may leverage the with case() context manager to branch out your DAG so that no other tasks are executed if some condition is satisfied.

Example flow:

from random import random
from prefect import task, Flow, case

def check_condition():
    return random() > 0.5

def action_if_true():
    return "Continuing execution..."

def another_action(val):

def stop_flow_run():
    print("Stopping the flow run...")

with Flow("conditional-branches") as flow:
    cond = check_condition()

    with case(cond, True):
        val = action_if_true()

    with case(cond, False):
        val = stop_flow_run()