r/ProgrammerTIL • u/thataccountforporn • Mar 06 '18
Python [Python] TIL you can use multiple context managers at once in one with statement
That means you can do
with A() as a, B() as b:
do_something(a, b)instead of doing
with A() as a:
with B() as b:
do_something(a, b)
67
Upvotes
23
u/c3534l Mar 06 '18
Python's obscure features are all super obvious once you learn what they are.
14
u/o11c Mar 06 '18
For a dynamic number of context managers, or if you want to open them at different times but close them all at once (to avoid deep indents), there's also:
1
u/BlackBloke Mar 06 '18
I think I used this for reading and writing once.
1
u/chanamasala4life Apr 06 '18
You can also rename multiple imports at the same time:
Not really totally related, but your TIL reminded me of mine.
0
u/[deleted] Mar 06 '18
[deleted] — view deleted comment