<@ULVA73B9P> how to check if a future is completed...
# ask-community
k
@Marvin how to check if a future is completed succesfully or not
m
thought for 349.6 seconds
Do you mean a Prefect future (from `task.submit`/`flow.submit`) or a Python `concurrent.futures`/`asyncio` future? Below is how to do it in Prefect 3.x; if you meant Python futures, I can share that too. In Prefect 3.x, a
PrefectFuture
gives you a few ways to check completion/success: - Blocking and raise on failure (simplest)
Copy code
try:
    result = fut.result()  # blocks; raises on Failed/Cancelled/Crashed
    # success
except Exception as exc:
    # not successful
- Blocking and inspect the state explicitly
Copy code
from prefect.schemas import StateType

fut.wait()                 # blocks until terminal state
state = fut.get_state()    # retrieve final state
if state.type == StateType.COMPLETED:
    val = fut.result(raise_on_failure=False)  # won't raise now
    # success
else:
    # not successful (Failed/Cancelled/Crashed/etc.)
- Non-blocking check (polling)
Copy code
from prefect.schemas import StateType

if fut.done():             # True when in a terminal state
    state = fut.get_state()
    if state.type == StateType.COMPLETED:
        # success
    else:
        # not successful
else:
    # still running / pending
- Check for an exception without raising
Copy code
exc = fut.exception()      # returns an Exception if run failed/cancelled/crashed; otherwise None
if exc is None:
    # Either still running or completed successfully — use fut.done() or state to distinguish
    if fut.done():
        # success
else:
    # not successful
- Many futures at once
Copy code
from prefect.futures import wait

done, not_done = wait([f1, f2, f3])  # blocks until terminal states or timeout
for fut in done:
    st = fut.get_state()
    if st.type == StateType.COMPLETED:
        # success
    else:
        # not successful
Quick notes: -
fut.result(timeout=None, raise_on_failure=True)
blocks and raises on non-success states. -
fut.wait(timeout=None)
blocks until terminal state; it does not return the state, so call
fut.get_state()
afterward. -
fut.done()
returns True if the future is in any terminal state (Completed, Failed, Cancelled, Crashed). -
fut.exception()
returns the underlying exception if the run failed/cancelled/crashed; otherwise
None
(it may still be running, so pair with
done()
if you need to know it’s completed). If you were asking about Python
concurrent.futures
or
asyncio.Future
, let me know which one and I’ll tailor the examples.