Is this a bug? (__eq__, __lt__, etc.)

Steve Holden sholden at holdenweb.com
Tue May 8 04:44:59 CEST 2001


"Edw88253" <none at dev.null> wrote in message
news:tfejhh5vbc3p34 at news.supernews.com...
> The __eq__, __gt__, etc. methods seem to be called more often than
necessary
> when I compare two objects.  Is this a bug or a feature?  (See transcript
> below)  If it's a feature, what's it accomplishing?  E.g., what are the
> semantics if __lt__(a,b) returns true the first time and false the second
> time?
>
> class A:
>     def __init__(self, c): self.c=c
>     def __cmp__(s,o):
>         print 'cmp', s.c, o.c
>         return NotImplemented
>     def __eq__(s,o):
>         print 'eq', s.c, o.c
>         return NotImplemented
>     def __lt__(s,o):
>         print 'lt', s.c, o.c
>         return NotImplemented
>     def __gt__(s,o):
>         print 'gt', s.c, o.c
>         return NotImplemented
>
> >>> (a, b) = (A('a'), A('b'))
> >>> a == b
> eq a b
> eq b a
> eq b a
> eq a b
> cmp a b
> cmp b a
> 0
> >>> a < b
> lt a b
> gt b a
> gt b a
> lt a b
> cmp a b
> cmp b a
> 0
>
> (I sent this question out before as part of a post, but didn't get any
> responses, so I thought I'd try again..  I would appreciate it if you
could
> cc responses to edloper at gradient.cis.upenn.edu, but I'll try to keep an
eye
> out for responses on the newsgroup too..)
>
Erm, what's this "NotImplemented" thingy, then? Your code as is, run as a
program and not interactively, gave me:

    NameError: There is no variable named 'NotImplemented'

If I try setting it to strange values like None, I get:

    TypeError: comparison did not return an int

If I set NotImplemented to zero I get:

    cmp a b <__main__.A instance at 00769F5C> <__main__.A instance at
0076CC6C>
    cmp a b <__main__.A instance at 00769F5C> <__main__.A instance at
0076CC6C>

I modified your code slightly to verify the objects' identifiers.

Here's my code, COPIED AND PASTED:

NotImplemented = 0

class A:
    def __init__(self, c): self.c=c
    def __cmp__(s,o):
        print 'cmp', s.c, o.c, s, o
        return NotImplemented
    def __eq__(s,o):
        print 'eq', s.c, o.c, s, o
        return NotImplemented
    def __lt__(s,o):
        print 'lt', s.c, o.c, s, o
        return NotImplemented
    def __gt__(s,o):
        print 'gt', s.c, o.c, s, o
        return NotImplemented

(a, b) = (A('a'), A('b'))
a == b
a < b

Was yours? ;-)

regards
 Steve





More information about the Python-list mailing list