5 ms·
My favorite underused Python idiom
- svisser 11y ago> Notice data is defined inside the with block, but remains accessible once that block is exited (and the file object is auto-closed). This is the normal Python scoping rules at work. If you create (initially define) a variable in a block, it's also defined in the parent blocks - up until the function boundary. The with statement doesn't create a new scope and as such it's the same as variables defined outside a with statement.
- fancy_pantser 11y agoMaybe he's coming from Perl or something with narrow scoping.
- bbrazil 11y agoContext managers are quite powerful, you can use them for more than resource closing. They're handy to make instrumentation easier too, for example by allowing you put the code you want to count exceptions in in a with block as shown in http://www.slideshare.net/brianbrazil/python-ireland-monitoring-your-python-with-prometheus/25 http://www.slideshare.net/brianbrazil/python-ireland-monitor...
- ckv428 11y agoI've had success implementing context managers with page object models when testing with selenium. All page objects assume the same base page (e.g. the home page of the web app) and will return the browser to that page upon exiting the with block. It works really well.
- chronomex 11y agoWhat's with the forced email signup form?
- bashinator 11y agoCouldn't get rid of it, closed tab, didn't read article.
- rudolf0 11y agoI would not call this underused. Every Python tutorial I've ever read teaches this as the proper way to handle file IO, and explains what context managers are.
- Walkman 11y agoYeah and then you go to a company, where guys doing Python only programming for 3.5, 10, 15 years (really!) and never heard of context managers, or decorators...