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.
do something
consisting of many lines) you should probably put the loop and thesomething
into separate functions/methods, and makedata
a (return) parameter. Voilà, the scope is well defined then.do
loop in Python). I've taken this example from: effbot.org/zone/python-with-statement.htmdata
originally came from a file doesn't mean that you need to keep the file opened while you processdata
.data = open(path).read()
. This is equivalent to your second example.