<@ULVA73B9P> How can I mark a flow or task cancell...
# ask-marvin
z
@Marvin How can I mark a flow or task cancelled manually from inside the flow or task? I want to check a condition and if true mark the task/flow cancelled.
m
To conditionally cancel a flow or a task in Prefect, you can use the
fail
method provided by the Prefect API. Here is an example to illustrate how you can achieve this: ### To cancel a task: You can raise an exception to mark a task as failed:
Copy code
python
from prefect import flow, task

@task
def check_condition_and_fail():
    condition = True  # Replace with your actual condition
    if condition:
        raise ValueError("Condition met, cancelling the task.")
    return "Continue execution"

@flow
def my_flow():
    try:
        check_condition_and_fail()
    except ValueError as e:
        print(e)
        return  # Optionally perform cleanup or other actions

if __name__ == "__main__":
    my_flow()
### To cancel a flow: You can set the state to
Cancelled
when a specific condition is met:
Copy code
python
from prefect import flow, task
from prefect.engine import signals

@task
def some_task():
    return True  # Replace with your actual task logic

@flow
def my_flow():
    if some_task():
        raise signals.FAIL("Condition met, cancelling the flow.")
    return "Flow completed successfully"

if __name__ == "__main__":
    my_flow()
In this example, if the condition is met, a
ValueError
is raised, marking the task as failed, and the flow returns. For flows, throwing a
FAIL
signal achieves a similar intent by marking the flow as failed. ### Reference For further details, check the official Prefect documentation: - Prefect Flows - Prefect Tasks