PEP 601: Forbid return/break/continue breaking out of finally

Reading the references in the PEP it seems to me that most languages implement this kind of construct but have style guides and/or linters that reject it. I would support a proposal to add this to PEP 8 (if it isn’t already there). I also won’t have hard feelings if MicroPython decides not to implement it.

I note that the toy examples are somewhat misleading – the functionality that may be useful is a conditional return (or break etc.) inside a finally block.

For example the return in the __exit__ method in subprocess.py is actually correct, since a return from __exit__ re-raises the exception that it was originally handling, and the only exceptions it could be cancelling would be from if self.stdin: self.stdin.close() or another KeyboardInterrupt. The comment at the top of the try block hints that close() indeed can raise: “Flushing a BufferedWriter may raise an error”. Since we’re already inside error handling (__exit__) it is reasonable to assume that the author fully intended the behavior of cancelling of such errors.

3 Likes