Coding style and else statements

Ben Finney bignose+hates-spam at benfinney.id.au
Thu Aug 31 22:40:58 EDT 2006


matt.newville at gmail.com writes:

> > 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 chose this to more clearly contrast with the example to which I was
responding; same number of statements but clearer control flow.

> I wouldn't discount:
>
> def foo(thing):
>     result = -1
>     if thing:
>         result = thing+1
>     return result

Yes, that would be my preferred form in most cases.

If I'm writing a function that returns a value, I like to make it
clear by the symmetry of 'result = DefaultValue' and 'return result'
that that's the main gist of the function; the rest of the function is
then geared around changing 'result' before the 'return result'
statement.

My way of being friendly to the reader (admittedly, assuming the
reader will read code similar to the way I read it).

-- 
 \     "Sittin' on the fence, that's a dangerous course / You can even |
  `\    catch a bullet from the peace-keeping force"  -- Dire Straits, |
_o__)                                   _Once Upon A Time In The West_ |
Ben Finney




More information about the Python-list mailing list