question of style

Dave Angel davea at ieee.org
Sat Jul 4 09:31:44 EDT 2009


upwestdon wrote:
> On Jul 2, 1:23 pm, Simon Forman <sajmik... at gmail.com> wrote:
>   
>> Hey I was hoping to get your opinions on a sort of minor stylistic
>> point.
>> These two snippets of code are functionally identical. Which would you
>> use and why?
>> The first one is easier [for me anyway] to read and understand, but
>> slightly less efficient, while the second is [marginally] harder to
>> follow but more efficient.
>>
>> ## First snippet
>>
>> if self.higher is self.lower is None: return
>> if self.lower is None: return self.higher
>> if self.higher is None: return self.lower
>>
>> ## Second snippet
>>
>> if self.higher is None:
>>     if self.lower is None:
>>         return
>>     return self.lower
>> if self.lower is None:
>>     return self.higher
>>
>> What do you think?
>>
>> (One minor point: in the first snippet, the "is None" in the first
>> line is superfluous in the context in which it will be used, the only
>> time "self.lower is self.higher" will be true is when they are both
>> None.)
>>     
>
> How about just:
>
> if not (self.higher and self.lower):
>     return self.higher or self.lower
>
>   
But if self.higher is 0  and self.lower is None, this'll return None, 
which wasn't the original intent.

Without having some documented constraints on the self.higher and lower 
types and values, it's difficult to simplify further.




More information about the Python-list mailing list