7

How can I spread a long with clause in Python over multiple lines? Right now, I have

    with self.context_manager_one(some, parameters, that, are, passed) \
            as return_value_one, \
            self.context_manager_two(self.p, slice(None), None) \
            as return_value_two:

I would like to follow Google's Python style guide, which proscribes backslash line continuation.

m00am
  • 5,910
  • 11
  • 53
  • 69
Neil G
  • 32,138
  • 39
  • 156
  • 257
  • How about splitting into two context managers first? – alecxe May 04 '13 at 18:35
  • @alecxe: What do you mean? – Neil G May 04 '13 at 18:36
  • I mean just `with ... as return_value_two` inside `with ... as return_value_one`. – alecxe May 04 '13 at 18:37
  • Right, that saves one `\\`, but is there no way to use parentheses to do this? Looking at the parse tree, it doesn't seem possible. – Neil G May 04 '13 at 18:38
  • I'd just define context managers outside the with statement or use `nested`: http://docs.python.org/2/library/contextlib.html. Hope that helps. – alecxe May 04 '13 at 18:40
  • 1
    @alecxe: nested is gone… – Neil G May 04 '13 at 18:40
  • @alecxe: Okay, thanks. Too bad Python doesn't allow parentheses with the `with` statement. It seems an arbitrary limitation. – Neil G May 04 '13 at 18:46
  • 2
    You can add `()` around an expression: `with (open("c:\\temp\\23", "w")) as f: pass` worked for me, and so should `with (self.context_manager_one(some, parameters, that, are, passed)) as return_value_one, (self.context_manager_two(self.p, slice(None), None)) as return_value_two:`. There you can add line breaks as you want. – glglgl May 27 '13 at 12:13
  • 2
    Related: https://stackoverflow.com/questions/31039022/python-multi-line-with-statement – User Feb 23 '20 at 11:51
  • 1
    Does this answer your question? [Python multi-line with statement](https://stackoverflow.com/questions/31039022/python-multi-line-with-statement) – User Feb 23 '20 at 11:54

1 Answers1

0

This is fixed in Python 3.10!

https://github.com/we-like-parsers/pegen/issues/229

https://bugs.python.org/issue12782

Neil G
  • 32,138
  • 39
  • 156
  • 257