My favorite underused Python idiom
migrateup.com
My favorite underused Python idiom
1–9 of 9 posts
Re: My favorite underused Python idiom
#2The with statement doesn't create a new scope and as such it's the same as variables defined outside a with statement.
Re: My favorite underused Python idiom
#3Re: My favorite underused Python idiom
#4Re: My favorite underused Python idiom
#5Re: My favorite underused Python idiom
#6What's with the forced email signup form?
Re: My favorite underused Python idiom
#7> 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…
Re: My favorite underused Python idiom
#8I 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.
Re: My favorite underused Python idiom
#9Context 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...