Coding style and else statements

matt.newville at gmail.com matt.newville at gmail.com
Thu Aug 31 21:36:59 EDT 2006


> To my eyes, that's less readable than, and has no benefit over, the
> following:
>
>     def foo(thing):
>         if thing:
>             result = thing+1
>         else:
>             result = -1
>         return result

I wouldn't discount:

def foo(thing):
    result = -1
    if thing:
        result = thing+1
    return result

especially if "thing" is the less expected case.  This
puts the "more likely" result first, followed by checks
that might modify that result.

But, I also try to avoid adding 1 to things that I test
for Truth:

>>> x = 8
>>> foo(x)
9
>>> foo(x>1)
2
>>> foo(x and 1)
2
>>> foo(x or 1)
9

--Matt




More information about the Python-list mailing list