[Python-ideas] if expensive_computation() as x:

Chris Angelico rosuav at gmail.com
Fri Feb 14 22:06:34 CET 2014


On Sat, Feb 15, 2014 at 7:48 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, Feb 14, 2014 at 05:18:55AM -0500, Terry Reedy wrote:
>
>> I do not really understand the fear of indents that would cause one to
>> repeat calculations rather than write the actual logic.
>>
>>     x = expensive_computation_0():
>>     if x:
>>         # Do something with x...
>>     else:
>>         x = expensive_computation_1()
>>         if x:
>>             # Do something with x...
>
> That's really not very nice looking. It's okay with one or two levels,
> three at the most, but avoiding that sort of thing is why we have elif
> in the first place. So I wouldn't call it a *fear* of indents, more an
> dislike of excessive indentation.

More to the point, excessive _and inappropriate_ indentation. An
if/elif/elif/elif/else chain puts all the conditions at the same
level, and all the bodies at the same level (one further in than the
conditions). The intention is that they're all peers, not that they're
nested inside each other. Maybe the computer physically executes it as
a series of nested conditions (more likely, it's a series of
conditions with big fat GOTOs to get out of them), but logically and
conceptually, it's not that, so it shouldn't be written that way.
Since Python, unlike C, doesn't let you assign inside a condition (and
C doesn't let you declare inside a condition - nor does C++, though at
least there you can declare inside a for loop, which is the most
common case), you need to warp your code somewhat around what the
language supports; in my opinion, the less warping, the better, which
means either a dummy while loop or a nested function. (The nested
function might be clearer in a lot of situations, but having to
declare too many nonlocals may damage that, which would be a point in
favour of while/break. It'd be nice to just say "nonlocal *" meaning
"everything that looks local isn't", but that's probably a nightmare
for the interpreter.)

ChrisA


More information about the Python-ideas mailing list