multiple with statement in one line for python

169 Views Asked by At

Can I write multiple with statement in one line in python? For

with suppress(Exception): del a;
with suppress(Exception): del b;

is there something like?

with suppress(Exception): del a;|| with suppress(Exception): del b;
1

There are 1 best solutions below

0
ti7 On

No, this is not practical or supported and will make your code worse and harder to understand and maintain

If you manage to accomplish doing so (which is a feature of Python!), it won't be Pythonic

To quote from the Zen of Python

Sparse is better than dense.
Readability counts.

That said, you may really have have a technical reason to do this (for example, I've wanted to write very terse code when doing evils in a pdb REPL) - in such a case, try to package the full logic you really want to do and transform it into what you need

  • make a new function and call it
  • make a new context manager with all the desired functionality
  • make a library and import it
  • "just don't do that" (if something seems really awkward, there may be a better way!)
  • exec a magic string (see also: this is evil)