Hacker News new | comments | show | ask | jobs | submit login
My favorite underused Python idiom (migrateup.com)
15 points by redsymbol 880 days ago | hide | past | web | 8 comments | favorite



I 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.


Yeah 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...


> 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.


Maybe he's coming from Perl or something with narrow scoping.


What's with the forced email signup form?


Couldn't get rid of it, closed tab, didn't read article.


Context 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-monitor...


I'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.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: