3 ms·
I write a lot of Python and didn't know about this despite it being a 2015 blog post! The real kicker for me is: * [ExitStack] easily scales up to many resourc
by davidwf 6y ago
I write a lot of Python and didn't know about this despite it being a 2015 blog post! The real kicker for me is:
* [ExitStack] easily scales up to many resources (including a dynamic number that's acquired in a loop)
- jnwatson 6y agoIn particular ExitStacks are useful when you have 0 or 1 resources. It allows a sort of null-context manager for when the number of resources you have to allocate might be 0.
- hchasestevens 6y agoDo be aware that https://docs.python.org/3.9/library/contextlib.html#contextlib.nullcontext https://docs.python.org/3.9/library/contextlib.html#contextl... also exists as of 3.7 -- you can do ctx_mgr = foo() if bar else nullcontext() with ctx_mgr: ... if you like.
- BerislavLopac 6y agoOr even, from Python 3.8: with (ctx_mgr := foo() if bar else nullcontext()): ...