Running post tasks even if the main task fail

Open
#980 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
cli

Research direction

Start by tracing how pre and post tasks are executed around main_task and how unhandled exceptions propagate. Define the failure-path behavior so my_post_task performs cleanup after main_task fails, then verify both successful and failing task runs.

Written by the indexing model from the issue text.

Description

Hello. I was wondering if there's a way to make sure that a post task runs even if the main task fails with an unhandled exception? Here's a simplified version of my code to illustrate the issue:

@task()
def my_pre_task(ctx):
    # Do some resource provisioning needed by the task


@task()
def my_post_task(ctx):
    # Perform resource cleanup
    # This should always run, but it won't if the main task fails with an unhandled exception


@task(pre=[my_pre_task], post=[my_post_task])
def main_task(ctx):
    # Do something that could also result in an unhandled exception

I know that I can wrap the main_task in a try/finally, but I'd rather not do this if I can find a more elegant solution. I was hoping there was something like post_run_on_failure=True that I could use, or a finally task that behaves like a post but always run.

Dominant language
Python
Stars
4.8k
Forks
412
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from pyinvoke/invoke

All issues in pyinvoke/invoke

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.