question of style

Lie Ryan lie.1296 at gmail.com
Fri Jul 3 02:05:06 EDT 2009


Tim Harig wrote:
>> Speaking only to the style issue, when I've wanted to do something like
>> that, I find:
>>        if self.higher is None is self.lower:
>> more readable, by making clear they are both being compared to a
>> constant, rather than compared to each other.
> 
> By comparing them to *any* constant with 'is' you end up with the same
> potential problems as to whether something with a value of None is actually
> None?  

Oh really? None is a Singleton and all None always point to the same
None object. And the fact that it is impossible to override `is`
operator is the reason for the "is None" idiom.

This does not happen with other objects though (except if you make them
as Singletons as well), and in case of immutable, you may get bugs due
to python's optimizing small integers.

> With equality operators
> everything is either the same or it isn't.   

How about:
class Fake(object):
    def __eq__(self, other):
        return True

we uses `is` when we want to make sure an object is really the same
object as another, not just an equivalent object.

I can start from the first
> variable and compare it to the second then to the third then ...  In the
> case of the inequality, I have to start with the first and compare it to
> all of the rest to make sure that none are the same.  Then I have to do the
> same for each with the remaining.  This is much more difficult to do in my
> head.  I requires much more thought, better left to a computer, when
> evaluating the expression for myself.  Therefore, equalites are quick and
> easy to keep straight whereas any inequalites are more error prone when
> trying to evaluate how a section of code will react under different
> circumstances.
> 
>> I do draw the line at two, though, and with three or more I'll
>> paren-up a list of parallel comparisons:
> 
> As long as everything is an equality, then I don't mind comparing to the
> end of an 70 column line.  Mixed types of equalities or inequalities
> require too many operations mentally evaluate safely.

Personally, I'd only chain inequality for something like this:
if 0 < x < 10:



More information about the Python-list mailing list