

My favorite underused Python idiom - redsymbol
http://migrateup.com/favorite-underused-python-idiom/

======
rudolf0
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
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
> 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
Maybe he's coming from Perl or something with narrow scoping.

------
chronomex
What's with the forced email signup form?

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

------
bbrazil
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...](http://www.slideshare.net/brianbrazil/python-ireland-monitoring-
your-python-with-prometheus/25)

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

