A newbie question about class

Mark McEahern marklists at mceahern.com
Sun Feb 10 12:47:12 EST 2002


[newgene]
> Could you explain a little more why "is not" is better than "!="?

The short answer is that I don't think comparing something to None by
identity will ever raise an error.  Comparing it by magnitude might.

Python allows you to override magnitude comparison methods:  ==, !=, <, >,
<=, >=.  If you are using code written by somebody else, you don't know
whether they've accounted for comparison to None in their comparison
methods.  If you compare to None by identity, you bypass that whole issue
because comparison by identity ("is" and "is not") happens via id() and
that's not something you can override (as far as I know).

I recently ran into precisely this problem when I tried to feed FixedPoint
instances to PostgreSQL via PyPgSql.  PyPgSql was comparing to None by
magnitude.  FixedPoint's comparison method raised an error when other is
None.

So there you go.

Did that make sense?

For what it's worth, here's a simplification of FixedPoint that demonstrates
the problem.

#! /usr/bin/env python

class MyNumber:

    def __init__(self, value=0):
        try:
            self.value = float(value)
        except:
            raise TypeError("Can't convert to MyNumber: " + `value`)

    def __cmp__(self, other):
        x, y = normalize(self, other)
        return cmp(x, y)

def normalize(x, y):
    assert isinstance(x, MyNumber)
    if not isinstance(y, MyNumber):
        y = MyNumber(y)
    return x.value, y.value

m = MyNumber(2.0)

if m is not None:
    print "Hey, imagine that, we can compare to None by identity."
    print

# Now, try comparing m to None via the equality operator...

try:
    if m != None:
        print "Hey, I didn't think we could compare to None by magnitude!"
        print
except TypeError, e:
    print "Comparing to None by magnitude raises a TypeError:"
    print
    print e

## end

Cheers,

// mark





More information about the Python-list mailing list