[Python-ideas] "else if" as equivalent for "elif"

Andrew Barnert abarnert at yahoo.com
Wed Oct 21 16:01:04 EDT 2015


On Oct 21, 2015, at 12:26, MRAB <python at mrabarnett.plus.com> wrote:
> 
>> On 2015-10-21 19:16, Sven R. Kunze wrote:
>>> On 21.10.2015 20:05, Ryan Gonzalez wrote:
>>> The Python Zen says:
>>> 
>>> There should be one-- and preferably only one --obvious way to do it.
>>> 
>>> elif uses less typing, anyway. Why type 3 more characters when you
>>> really don't need to? :D
>> 
>> Because it's one of those "Python looks strange"? ;-)
> The C preprocessor has #elif. Is that strange too? :-)
> 
> (It could be argued that it _is_ strange that the C preprocessor has an
> explicitly-terminated "#if ... #endif", whereas the C language itself
> doesn't have an explicitly-terminated "if".)

C++ of course solved that by embedding a whole compile-time language that's even less like C than the preprocessor, where the clauses have to be bounded in angle brackets, removing all ambiguity and leading to nice readable things like this:

    typedef typename if_c<spam, SpamType,
        typename if_c<eggs, EggsType, CheeseType>::type>
        ::type type;

Compare to:

    if (spam) type = SpamType;
    else if (eggs) type = EggsType;
    else type = CheeseType;

The second one leaves it unclear to the reader that the final else is actually part of the second if which is itself controlled by the first if's else. If you indebted this "properly" it would be a lot uglier. Which is the whole problem elif is meant to solve. But the first version makes the tree structure the clearest thing in the whole construction, without needing elif, so it's clearly better. ;)



More information about the Python-ideas mailing list