[Python-ideas] Potential PEP: with/except
steve at pearwood.info
Tue Jan 22 17:17:23 EST 2019
On Tue, Jan 22, 2019 at 01:11:10PM -0700, Paul Ferrell wrote:
> I would like to propose that the syntax for 'with' blocks
> be changed such that they can be accompanied by 'except', 'finally',
> and/or 'else' blocks as per a standard 'try' block.
What benefit does this give apart from saving one line and one indent?
If either is in short supply, the code probably needs refactoring, not
The beauty of the current syntax is that try...except and with blocks
are fully independent, composable blocks which can be learned and
reasoned about seperately. You're proposing to add a new special-case
that adds a new block structure that has to be implemented, documented,
tested, maintained, taught and learned. It will inevitably lead to
questions on mailing lists, IRC and Stackoverflow asking what is the
difference between a separate try...with...except and a with...except,
and when to choose one or the other.
And of course then there will be the inevitable requests that we
generalise it to other blocks:
If this will allow us to write more expressive code, or do things we
couldn't easily do before, then it might be worthwhile to add this
But if all it does is save one line and one indent, then I believe it is
redundant and I would be against it.
More information about the Python-ideas