How does compare work?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Helmut Jarausch

    How does compare work?

    Hi,

    what does Python do if two objects aren't comparable (to my opinion)
    If I've understood "Python in a Nutschell" correctly it should raise an
    exception but it doesn't do for me.

    Here are two examples

    if 2 > '1' : print "greater"
    else : print "less_or_eq ual"

    prints less_or_equal

    and

    class C:
    def __init__(self): pass

    X=C()
    if 2 > X : print "greater"

    prints greater

    In both cases I don't get an exception.
    But I'd like to since these lead to hard-to-find bugs.

    Thanks for shedding some light on this.

    P.S. This is Python 2.4 (CVS)

    --
    Helmut Jarausch

    Lehrstuhl fuer Numerische Mathematik
    RWTH - Aachen University
    D 52056 Aachen, Germany
  • Terry Reedy

    #2
    Re: How does compare work?


    "Helmut Jarausch" <jarausch@skyne t.be> wrote in message
    news:40158680$0 $7044$ba620e4c@ news.skynet.be. ..[color=blue]
    > what does Python do if two objects aren't comparable (to my opinion)[/color]

    Sorry, Python does what it does, which is generally to compare any two
    objects unless explicitly disabled as with complex numbers or in
    user-written method of user class.
    [color=blue]
    > If I've understood "Python in a Nutschell" correctly it should raise an
    > exception but it doesn't do for me.[/color]

    Perhaps you could quote the line that mislead you, and someone could
    explain, or suggest a change to the author.

    Terry J. Reedy




    Comment

    • Inyeol Lee

      #3
      Re: How does compare work?

      On Mon, Jan 26, 2004 at 10:28:31PM +0100, Helmut Jarausch wrote:[color=blue]
      > Hi,
      >
      > what does Python do if two objects aren't comparable (to my opinion)
      > If I've understood "Python in a Nutschell" correctly it should raise an
      > exception but it doesn't do for me.
      >[/color]
      [color=blue]
      >From section 5.9 in Python 2.3.3 Reference manual;[/color]
      """
      The operators <, >, ==, >=, <=, and != compare the values of two
      objects. The objects need not have the same type. If both are numbers,
      they are converted to a common type. Otherwise,
      objects of different types always compare unequal, and are ordered
      consistently but arbitrarily.

      (This unusual definition of comparison was used to simplify the
      definition of operations like sorting and the in and not in operators.
      In the future, the comparison rules for objects of
      different types are likely to change.)
      """

      -Inyeol Lee

      Comment

      • Gerrit Holl

        #4
        Re: How does compare work?

        Inyeol Lee wrote:[color=blue]
        > (This unusual definition of comparison was used to simplify the
        > definition of operations like sorting and the in and not in operators.
        > In the future, the comparison rules for objects of
        > different types are likely to change.)
        > """[/color]

        When comparing mixed types becomes illegal, does that mean sorting a
        sequence of mixed types becomes illegal as well? Or will sort be a
        special case?

        yours,
        Gerrit.

        --
        136. If any one leave his house, run away, and then his wife go to
        another house, if then he return, and wishes to take his wife back:
        because he fled from his home and ran away, the wife of this runaway shall
        not return to her husband.
        -- 1780 BC, Hammurabi, Code of Law
        --
        PrePEP: Builtin path type

        Asperger's Syndrome - a personal approach:


        Comment

        • Jp Calderone

          #5
          Re: How does compare work?

          On Tue, Jan 27, 2004 at 02:16:51PM +0100, Gerrit Holl wrote:[color=blue]
          > Inyeol Lee wrote:[color=green]
          > > (This unusual definition of comparison was used to simplify the
          > > definition of operations like sorting and the in and not in operators.
          > > In the future, the comparison rules for objects of
          > > different types are likely to change.)
          > > """[/color]
          >
          > When comparing mixed types becomes illegal, does that mean sorting a
          > sequence of mixed types becomes illegal as well? Or will sort be a
          > special case?
          >[/color]

          There was discussion of another operation, "before", which could be used
          to order different types, but which would not be used by < or >.

          I forget if the final word on this idea was positive or negative, but I'm
          sure anyone interested could dig up the relevant thread on python-dev.

          Jp

          Comment

          • Helmut Jarausch

            #6
            Re: How does compare work?

            Terry Reedy wrote:[color=blue]
            > "Helmut Jarausch" <jarausch@skyne t.be> wrote in message
            > news:40158680$0 $7044$ba620e4c@ news.skynet.be. ..
            >[color=green]
            >>what does Python do if two objects aren't comparable (to my opinion)[/color]
            >
            >
            > Sorry, Python does what it does, which is generally to compare any two
            > objects unless explicitly disabled as with complex numbers or in
            > user-written method of user class.
            >
            >[color=green]
            >>If I've understood "Python in a Nutschell" correctly it should raise an
            >>exception but it doesn't do for me.[/color]
            >
            >
            > Perhaps you could quote the line that mislead you, and someone could
            > explain, or suggest a change to the author.
            >[/color]

            First let me say that IMHO this is a big misdesign of Python.
            I've come to Python from Perl since many posts convinced me that Python
            is safer - and mostly it is.
            But silently(!) comparing apples with pears is evil. E.g. the example I
            came across this was

            thresh=raw_inpu t('enter threshold')
            ....
            level=2
            ....
            if level > thresh :

            which failed miserably. By the way, Perl does convert the string to an
            integer silenty and, as most of the time, these Perl conversions are
            just what one wants, so here.
            Nevertheless, I'd prefer an exception in this case since automatic
            conversions can never be right in all circumstances.
            So this is a case where Python is a very dangerous language!

            For the quotation
            In my 'Python in a Nutshell' by Alex Martelli (a tremendously good
            book), 1st edition on page 91 (Special Methods) it reads
            __cmp__ ......
            ............... .
            When __cmp__ is also absent, order comparisons (<,<=,>,>=)
            raise exceptions. Equality comparisons (==,!=), in this case,
            become identity checks: x==y evaluates id(x)==id(y) (i.e.,
            x is y)

            end of quotation.
            I wish this were true for the current Python implementation.

            Helmut.

            --
            Helmut Jarausch

            Lehrstuhl fuer Numerische Mathematik
            RWTH - Aachen University
            D 52056 Aachen, Germany

            Comment

            • Helmut Jarausch

              #7
              Re: How does compare work?

              Terry Reedy wrote:[color=blue]
              > "Helmut Jarausch" <jarausch@skyne t.be> wrote in message
              > news:40158680$0 $7044$ba620e4c@ news.skynet.be. ..
              >[color=green]
              >>what does Python do if two objects aren't comparable (to my opinion)[/color]
              >
              >
              > Sorry, Python does what it does, which is generally to compare any two
              > objects unless explicitly disabled as with complex numbers or in
              > user-written method of user class.
              >
              >[color=green]
              >>If I've understood "Python in a Nutschell" correctly it should raise an
              >>exception but it doesn't do for me.[/color]
              >
              >
              > Perhaps you could quote the line that mislead you, and someone could
              > explain, or suggest a change to the author.
              >[/color]

              First let me say that IMHO this is a big misdesign of Python.
              I've come to Python from Perl since many posts convinced me that Python
              is safer - and mostly it is.
              But silently(!) comparing apples with pears is evil. E.g. the example I
              came across this was

              thresh=raw_inpu t('enter threshold')
              ....
              level=2
              ....
              if level > thresh :

              which failed miserably. By the way, Perl does convert the string to an
              integer silenty and, as most of the time, these Perl conversions are
              just what one wants, so here.
              Nevertheless, I'd prefer an exception in this case since automatic
              conversions can never be right in all circumstances.
              So this is a case where Python is a very dangerous language!

              For the quotation
              In my 'Python in a Nutshell' by Alex Martelli (a tremendously good
              book), 1st edition on page 91 (Special Methods) it reads
              __cmp__ ......
              ............... .
              When __cmp__ is also absent, order comparisons (<,<=,>,>=)
              raise exceptions. Equality comparisons (==,!=), in this case,
              become identity checks: x==y evaluates id(x)==id(y) (i.e.,
              x is y)

              end of quotation.
              I wish this were true for the current Python implementation.

              Helmut.

              --
              Helmut Jarausch

              Lehrstuhl fuer Numerische Mathematik
              RWTH - Aachen University
              D 52056 Aachen, Germany

              Comment

              • Aahz

                #8
                Re: How does compare work?

                In article <4016A368.90508 06@skynet.be>,
                Helmut Jarausch <jarausch@skyne t.be> wrote:[color=blue]
                >
                >First let me say that IMHO this is a big misdesign of Python.[/color]

                Guido has come around to this POV. However, being able to compare
                different types does have some defensibility. Your example of an ``if``
                isn't directly relevant; what's more important is the question of
                sorting a list containing arbitrary information. This is particularly
                true for the case of something like extracting keys from a dict -- you
                don't want an exception raised.

                What may well happen is that sort comparisons get a different set of
                special methods than relational operators.
                --
                Aahz (aahz@pythoncra ft.com) <*> http://www.pythoncraft.com/

                "The joy of coding Python should be in seeing short, concise, readable
                classes that express a lot of action in a small amount of clear code --
                not in reams of trivial code that bores the reader to death." --GvR

                Comment

                • Josiah Carlson

                  #9
                  Re: How does compare work?

                  > But silently(!) comparing apples with pears is evil. E.g. the example I[color=blue]
                  > came across this was
                  >
                  > thresh=raw_inpu t('enter threshold')
                  > ...
                  > level=2
                  > ...
                  > if level > thresh :
                  >
                  > which failed miserably. By the way, Perl does convert the string to an
                  > integer silenty and, as most of the time, these Perl conversions are
                  > just what one wants, so here.
                  > Nevertheless, I'd prefer an exception in this case since automatic
                  > conversions can never be right in all circumstances.
                  > So this is a case where Python is a very dangerous language![/color]

                  The comparison doesn't fail, it succeeds, just not the way you like. If
                  you want thresh to be an integer, perhaps you should say
                  thresh = int(raw_input(' enter threshold'))

                  Perhaps one way to alleviate the problem is to have a special kind of
                  input function:

                  def special_input(p rompt, typ):
                  a = None
                  while a is None:
                  if typ is int:
                  r = '-?[0-9]+'
                  #special cases for each kind of input
                  a = re.search(r, raw_input(promp t))
                  if a is not None:
                  return typ(a.group(0))

                  Maybe a more fully featured set of input functions would be useful to
                  include in the standard library. Perhaps someone should write an
                  example module and submit it.

                  - Josiah

                  Comment

                  • Mel Wilson

                    #10
                    Re: How does compare work?

                    In article <mailman.850.10 75209472.12720. python-list@python.org >,
                    Gerrit Holl <gerrit@nl.linu x.org> wrote:[color=blue]
                    >Inyeol Lee wrote:[color=green]
                    >> (This unusual definition of comparison was used to simplify the
                    >> definition of operations like sorting and the in and not in operators.
                    >> In the future, the comparison rules for objects of
                    >> different types are likely to change.)
                    >> """[/color]
                    >
                    >When comparing mixed types becomes illegal, does that mean sorting a
                    >sequence of mixed types becomes illegal as well? Or will sort be a
                    >special case?[/color]

                    Presumably there'd be a whole new set of comparisons that
                    would support inter-type < (e.g. for sorts) and == (e.g. for
                    dicts). Even then, what about PEP 326, which presumes to
                    define highest and lowest objects that can be compared with
                    anything?

                    Regards. Mel.

                    Comment

                    • Aahz

                      #11
                      PEP 326 is D-E-A-D (was Re: How does compare work?)

                      In article <eN+FAls/KHIb089yn@the-wire.com>,
                      Mel Wilson <mwilson@the-wire.com> wrote:[color=blue]
                      >
                      >Even then, what about PEP 326, which presumes to define highest and
                      >lowest objects that can be compared with anything?[/color]

                      What about it? ;-)

                      (Guido just posted a Pronouncement rejecting it.)
                      --
                      Aahz (aahz@pythoncra ft.com) <*> http://www.pythoncraft.com/

                      "The joy of coding Python should be in seeing short, concise, readable
                      classes that express a lot of action in a small amount of clear code --
                      not in reams of trivial code that bores the reader to death." --GvR

                      Comment

                      • Josiah Carlson

                        #12
                        Re: PEP 326 is D-E-A-D (big frownie face)

                        Aahz wrote:
                        [color=blue]
                        > In article <eN+FAls/KHIb089yn@the-wire.com>,
                        > Mel Wilson <mwilson@the-wire.com> wrote:
                        >[color=green]
                        >>Even then, what about PEP 326, which presumes to define highest and
                        >>lowest objects that can be compared with anything?[/color]
                        >
                        >
                        > What about it? ;-)
                        >
                        > (Guido just posted a Pronouncement rejecting it.)[/color]

                        When I get around to posting the final version with an example module,
                        people can still use it if they want.
                        - Josiah

                        Comment

                        • Alex Martelli

                          #13
                          Re: How does compare work?

                          On Tuesday 27 January 2004 06:44 pm, Helmut Jarausch wrote:
                          ...[color=blue]
                          > In my 'Python in a Nutshell' by Alex Martelli (a tremendously good
                          > book), 1st edition on page 91 (Special Methods) it reads
                          > __cmp__ ......
                          > ...............
                          > When __cmp__ is also absent, order comparisons (<,<=,>,>=)
                          > raise exceptions. Equality comparisons (==,!=), in this case,
                          > become identity checks: x==y evaluates id(x)==id(y) (i.e.,
                          > x is y)
                          >
                          > end of quotation.
                          > I wish this were true for the current Python implementation.[/color]

                          Thanks for pointing out the error in the first sentence you quote; what the
                          sentence _should_ say, to describe Python's current implementation, is that
                          when none of the specific (__lt__ etc) nor generic (__cmp__) methods are
                          present, comparisons of objects default to comparisons of their id() values.

                          I apologize for my mistake. Could I ask you to be so kind as to post this
                          issue to the errata page, http://www.oreilly.com/catalog/pythonian/errata/ ?
                          By far the best way to get future printings fixed is for a reader to submit
                          errata, so it goes through the editorial process and comes to me for fixing.

                          Thanks!


                          Alex


                          Comment

                          Working...