Python – ‘with open() as’ and Indentation

coding-styleindentationpython

I could not find any official recommended indentation for the following idiom (straight from http://effbot.org/zone/python-with-statement.htm):

with open(path) as f:
    data = f.read()
    do something with data

or:

with open(path) as f:
    data = f.read()
do something with data

IMHO, the first version is better at showing the scope, but the latter may prevent an excessive indentation. Is choosing one of those just a matter of taste? Or is there any authoritative source or established tradition to follow?


As a side note, I cannot help but think that with is quite apart from the other block-constructing Python keywords. For instance, there is no question about choosing between:

if condition:
    do something
    do something different

or:

if condition:
    do something
do something different

Since they do… well, something different.

Best Answer

I always use the second approach because it ensures that I don't hold the resource (file in your case) open longer than necessary.

Related Topic