Hi,

In Python, there are multiple [compound
statements](https://docs.python.org/3/reference/compound_stmts.html)
with the `else` keyword.

For example:

```
for x in iterable:
    if x == sentinel:
        break
else:
    print("Sentinel not found.")
```

or:

```
try:
    do_something_sensitive()
except MyError:
    print("Oops!")
else:
    print("We're all safe.")
```

In my situation, I would like to mix the `with` statement with `else`.
In this case I would like that if no exception is raised within the
`with` to run the `else` part.

For example:

```
with my_context():
    do_something_sensitive()
else:
    print("We're all safe.")
```

Now imagine that in my `try .. except` block I have some heavy setup
to do before `do_something_sensitive()` and some heavy cleanup when
the exception occurs.

I'd like my context manager to do the preparation work, execute the
body, and cleanup. Or execute my else block only if there is no
exception.

Is there already a way to accomplish this in Python or can this be a
nice to have?

Regards,
Jimmy
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EAMYECTRMYSXYYYCKA3BPPFUKA3IPUW5/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to