top | item 9759069

My favorite underused Python idiom

15 points| redsymbol | 10 years ago |migrateup.com

8 comments

order
[+] rudolf0|10 years ago|reply
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.
[+] Walkman|10 years ago|reply
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...
[+] svisser|10 years ago|reply
> 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|10 years ago|reply
Maybe he's coming from Perl or something with narrow scoping.
[+] chronomex|10 years ago|reply
What's with the forced email signup form?
[+] bashinator|10 years ago|reply
Couldn't get rid of it, closed tab, didn't read article.
[+] bbrazil|10 years ago|reply
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...
[+] ckv428|10 years ago|reply
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.