[Python-Dev] PEP 8 update

Steven D'Aprano steve at pearwood.info
Tue Apr 7 05:02:55 CEST 2015


On Tue, Apr 07, 2015 at 03:11:30AM +0100, Rob Cliffe wrote:

> As a matter of interest, how far away from mainstream am I in 
> preferring, *in this particular example* (obviously it might be 
> different for more complicated computation),
> 
>     def foo(x):
>         return math.sqrt(x) if x >= 0 else None
> 
> I probably have a personal bias towards compact code, but it does seem 
> to me that the latter says exactly what it means, no more and no less, 
> and therefore is somewhat more readable.  (Easier to keep the reader's 
> attention for 32 non-whitespace characters than 40.)

In my opinion, code like that is a good example of why the ternary if 
operator was resisted for so long :-) Sometimes you can have code which 
is just too compact.

My own preference would be:

    def foo(x):
        if x >= 0: 
            return math.sqrt(x)
        return None

but I'm not terribly fussed about whether the "else" is added or not, 
whether the return is on the same line as the if, and other minor 
variations. 

-- 
Steve


More information about the Python-Dev mailing list