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

Chris Angelico rosuav at gmail.com
Sat Feb 15 01:49:31 CET 2014


On Sat, Feb 15, 2014 at 9:02 AM, Terry Reedy <tjreedy at udel.edu> wrote:
>> 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,
>
>
> But they are *not* peers.
>
>
>> not that they're nested inside each other.
>
>
> But logically, they are.
>

C has a switch statement that looks like this:

switch (expr)
{
    case value1:
        code1;
        break;
    case value2:
        code2;
        break;
    case value3:
        code3;
        break;
    case value4:
        code4;
        break;
    default:
        code5;
        break;
}

Are the case statements peers? The intention is usually that they are.
One does not indent each case statement equally to its preceding code
block, ever-increasing down the page.

What if we rewrite this with nothing but if and else?

x = expr;
if (x == value1)
    code1;
else
    if (x == value2)
        code2;
    else
        if (x == value3)
            code3;
        else
            if (x == value4)
                code4;
            else
                code5;

Tell me, please, why code4 and code5 are at equal indentation, but all
the other code blocks are different. In Python, we could use a
dictionary:

switch = {
    value1: lambda: code1,
    value2: lambda: code2,
    value3: lambda: code3,
    value4: lambda: code4,
    None: lambda: code5
}
switch.get(expr, switch[None])()

Once again, they're all peers. And if you define all the functions out
of line, they'll still be peers, both in definition and in execution.
Not one of them depends on any other. There is no sane and logical
reason to indent each one further than the others, because *to the
programmer* they are peers.

And that's my point. No matter how the *computer* sees them, the
*programmer* sees them as peers. Adding an additional option to the
list should not change the indentation level of any other, because the
logical structure of the code hasn't changed.

ChrisA


More information about the Python-ideas mailing list