Result of ``a is b''

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Carl Banks

    #16
    Re: Result of ``a is b''

    Andrew Koenig wrote:[color=blue]
    >
    >
    > "Axel Boldt" <axelboldt@yaho o.com> wrote in message
    > news:40200384.0 403161255.7fca7 a8c@posting.goo gle.com...
    >[color=green]
    >> Wow. So it seems that the action of "is" on immutables is unspecified
    >> and implementation dependent, thus useless to the programmer.[/color]
    >
    > Hardly. It has two fundamental properties, which can sometimes be useful:
    >
    > 1) If x and y refer to the same object, "x is y" yields True.
    >
    > 2) If "x is y" yields True, "x==y" also yields True. Equivalently, if
    > "x==y" yields False, "x is y" also yields False.[/color]



    Python 2.2.3c1 (#12, May 27 2003, 21:32:04)
    [GCC 2.95.4 20011002 (Debian prerelease)] on linux2
    Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
    >>> class a:[/color][/color][/color]
    .... def __eq__(x,y): return 0
    ....[color=blue][color=green][color=darkred]
    >>> b = a()
    >>> b is b[/color][/color][/color]
    1[color=blue][color=green][color=darkred]
    >>> b == b[/color][/color][/color]
    0


    So I don't think we can call it a "fundamenta l property" (unless the
    language has changed, which actually wouldn't surprise me).


    --
    CARL BANKS http://www.aerojockey.com/software
    "If you believe in yourself, drink your school, stay on drugs, and
    don't do milk, you can get work."
    -- Parody of Mr. T from a Robert Smigel Cartoon

    Comment

    • Carl Banks

      #17
      Re: Result of ``a is b''

      David MacQuigg wrote:[color=blue]
      > On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news@ph ysics.mcmaster. ca
      > (David M. Cooke) wrote:
      >[color=green]
      >>Personally, almost all my uses of 'is' are of the form 'x is None' or
      >>'x is not None'.[/color]
      >
      > Here are some more test results (averaging 10,000 evaluations in a
      > tight loop):
      >
      > time (sec) %
      > Test 1: 3.68E-007 100.0 F is False
      > Test 2: 4.87E-007 132.1 F == False
      > Test 3: 3.71E-007 100.0 N is None
      > Test 4: 5.51E-007 148.6 N == None
      >
      > The '== None' test is 49% slower than 'is None', but in absolute time,
      > the difference is only 180nec (on my new, but not top-speed PC). So
      > it would take about 10 million of these comparisons in a short time to
      > make a noticable difference to the user.
      >
      > I can't see where the 'is' test would *ever* be needed for the above
      > comparisons.[/color]


      Say you define the following class:

      class SomeRankedObjec t:
      def __init__(self,r ank):
      self.rank = rank
      def __cmp__(self,ot her):
      return cmp(self.rank,o ther.rank)


      Now, try to test it against None with "==":

      x = SomeRankedObjec t()
      x == None


      Oops, the Python interpretter just chewed you out for trying to access
      the nonexistent 'rank' attribute of the None object.

      If you want to test whether two expressions are the same object, use
      "is". Otherwise, use "==". Period. It's as close to an absolute
      rule as you'll ever find in programming.


      --
      CARL BANKS http://www.aerojockey.com/software
      "If you believe in yourself, drink your school, stay on drugs, and
      don't do milk, you can get work."
      -- Parody of Mr. T from a Robert Smigel Cartoon

      Comment

      • Asun Friere

        #18
        Re: Result of ``a is b''

        Skip Montanaro <skip@pobox.com > wrote in message news:<mailman.5 2.1079472192.74 2.python-list@python.org >...
        [color=blue]
        > No, its behavior is quite well-specified. It does a pointer comparison.
        > Here is my "is" rule:
        >
        > Use "is" to compare two objects only if one is explicitly known to be a
        > singleton defined by the language (None, Ellipsis, True, False).
        >
        > and its corrolary:
        >
        > Never use "is" to compare two programmer-defined variables.
        >[/color]
        What about when it is an object explicitly known to be singleton
        defined by the programmer. ;)

        Another possible use, would be to type test, eg. 'foo.__class__ is
        Foo', bearing in mind that one should avoid type testing in favour of
        polymorphism.

        Comment

        • Axel Boldt

          #19
          Re: Result of ``a is b''

          "Andrew Koenig" <ark@acm.org> wrote[color=blue]
          > "Axel Boldt" <axelboldt@yaho o.com> wrote[/color]
          [color=blue][color=green]
          > > Maybe one could redefine "is" on immutables as follows: for strings
          > > and numbers it acts as "==", for tuples it acts as componentwise "is".
          > > That would be a more useful operator IMHO.[/color]
          >
          > Can you give a realistic example of code that would benefit from such a
          > change?[/color]

          Well, componentwise "is" on tupels is clearly useful, and not
          available with a single operator right now. On the other hand, I don't
          think there can be any realistic example where the current version of
          "is" on immutables would be useful. Why would anybody ever want to
          know whether two strings or tupels are internally stored at the same
          location, other than to deduce details of the Python implementation?
          In addition, I claim that my redefinition avoids hard to find bugs:
          it's entirely possible that some people use "is" on strings, in the
          mistaken belief (based on some small examples) that it is faster and
          that Python always stores equal strings at the same location [I was
          about to do just that, and that's why I started this whole thread].
          Their programs may run correctly on some machines and not on others.
          Thirdly, my redefinition would reduce the number of unspecified
          implementation dependencies of the language. Note that "is" for
          mutable objects is an important operator with well-defined semantics
          and is not implementation dependent at all, only its behavior for
          immutable objects is.

          Lastly, using my redefinition of "is", we have the following nice
          property for all objects a and b (mutable or immutable):

          a is b iff in any code block not containing "id()" or "is", any
          (or all) occurrances of a can be replaced by b, with
          identical results

          In the current implementation, the above equivalence only holds if we
          remove "not containing id() or is", and then the statement becomes a
          mere tautology without nutritious value.

          Axel

          Comment

          • David MacQuigg

            #20
            Re: Result of ``a is b''

            On Wed, 17 Mar 2004 02:42:49 GMT, Carl Banks
            <imbosol@aerojo ckey.invalid> wrote:
            [color=blue]
            >David MacQuigg wrote:[color=green]
            >> On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news@ph ysics.mcmaster. ca
            >> (David M. Cooke) wrote:
            >>[color=darkred]
            >>>Personally , almost all my uses of 'is' are of the form 'x is None' or
            >>>'x is not None'.[/color]
            >>
            >> Here are some more test results (averaging 10,000 evaluations in a
            >> tight loop):
            >>
            >> time (sec) %
            >> Test 1: 3.68E-007 100.0 F is False
            >> Test 2: 4.87E-007 132.1 F == False
            >> Test 3: 3.71E-007 100.0 N is None
            >> Test 4: 5.51E-007 148.6 N == None
            >>
            >> The '== None' test is 49% slower than 'is None', but in absolute time,
            >> the difference is only 180nec (on my new, but not top-speed PC). So
            >> it would take about 10 million of these comparisons in a short time to
            >> make a noticable difference to the user.
            >>
            >> I can't see where the 'is' test would *ever* be needed for the above
            >> comparisons.[/color]
            >
            >
            >Say you define the following class:
            >
            > class SomeRankedObjec t:
            > def __init__(self,r ank):
            > self.rank = rank
            > def __cmp__(self,ot her):
            > return cmp(self.rank,o ther.rank)
            >
            >
            >Now, try to test it against None with "==":
            >
            > x = SomeRankedObjec t()
            > x == None
            >
            >
            >Oops, the Python interpretter just chewed you out for trying to access
            >the nonexistent 'rank' attribute of the None object.[/color]

            Here is the test using Python 2.3.3:
            [color=blue][color=green][color=darkred]
            >>> x = SomeRankedObjec t()[/color][/color][/color]
            ....
            TypeError: __init__() takes exactly 2 arguments (1 given) <== AS
            EXPECTED[color=blue][color=green][color=darkred]
            >>> x = SomeRankedObjec t(17)
            >>> x == None[/color][/color][/color]
            False <== AS EXPECTED[color=blue][color=green][color=darkred]
            >>>[/color][/color][/color]
            Which version of Python are you using?
            [color=blue]
            >If you want to test whether two expressions are the same object, use
            >"is". Otherwise, use "==". Period. It's as close to an absolute
            >rule as you'll ever find in programming.[/color]

            Your missing the point. The question is why do we ever need to test
            'x is None' instead of 'x == None'.

            We should keep the definitions of 'is' and '==' as they are, but
            discourage the use of 'is' unless you really do care if the tested
            objects are the same objects in memory.

            The importance of this is that implementation can change, even for
            something as simple as the None object. We just had a long discussion
            on enhancing the Reload() function, and concluded that the desired
            change (updating all references to reloaded objects) would require
            preserving a unique identity for simple objects like 'a = 2', 'b =
            None', etc., in the reloaded module. So if this change is made, you
            might find in some future version of Python that 'b is c' returns
            False even though they have both been set to None.

            Here is my "is" rule:

            Use 'is' to compare two references only if it is important that
            they refer to the same object in memory.

            and its corrolary:

            Use '==' if all you are concerned about is equality of value.

            -- Dave

            Comment

            • Terry Reedy

              #21
              Re: Result of ``a is b''


              "Axel Boldt" <axelboldt@yaho o.com> wrote in message
              news:40200384.0 403170530.57b6b ba4@posting.goo gle.com...[color=blue]
              > "is" on immutables would be useful. Why would anybody ever want to
              > know whether two strings or tupels are internally stored at the same
              > location, other than to deduce details of the Python implementation?[/color]

              Deducing details of the implementation *is*, for people with a certain
              curiosity, a legitimate usage, in spite of your distain for such.
              Explaining the bahavior of

              a=[1]
              b=a
              a[0]=2
              print b

              is another use for 'is'.

              Terry J. Reedy




              Comment

              • Andrew Koenig

                #22
                Re: Result of ``a is b''

                "Terry Reedy" <tjreedy@udel.e du> wrote in message
                news:mailman.97 .1079541755.742 .python-list@python.org ...
                [color=blue]
                > Deducing details of the implementation *is*, for people with a certain
                > curiosity, a legitimate usage, in spite of your distain for such.
                > Explaining the bahavior of
                >
                > a=[1]
                > b=a
                > a[0]=2
                > print b
                >
                > is another use for 'is'.[/color]

                Lists are mutable, so there's no proposal to change the behavior of "is" in
                this context.


                Comment

                • Andrew Koenig

                  #23
                  Re: Result of ``a is b''

                  "Axel Boldt" <axelboldt@yaho o.com> wrote in message
                  news:40200384.0 403170530.57b6b ba4@posting.goo gle.com...
                  [color=blue]
                  > Lastly, using my redefinition of "is", we have the following nice
                  > property for all objects a and b (mutable or immutable):
                  >
                  > a is b iff in any code block not containing "id()" or "is", any
                  > (or all) occurrances of a can be replaced by b, with
                  > identical results[/color]

                  Interesting idea. Perhaps you should consider writing a PEP.


                  Comment

                  • Axel Boldt

                    #24
                    Re: Result of ``a is b''

                    "Terry Reedy" <tjreedy@udel.e du> wrote
                    [color=blue]
                    > "Axel Boldt" <axelboldt@yaho o.com> wrote[/color]
                    [color=blue][color=green]
                    > > "is" on immutables would be useful. Why would anybody ever want to
                    > > know whether two strings or tupels are internally stored at the same
                    > > location, other than to deduce details of the Python implementation?[/color]
                    >
                    > Deducing details of the implementation *is*, for people with a certain
                    > curiosity, a legitimate usage, in spite of your distain for such.[/color]

                    No disdain whatsoever, I do it all the time myself. However, even
                    after my proposed redefinition of "is" for immutables, the function
                    id() would remain available for the curious.
                    [color=blue]
                    > Explaining the bahavior of
                    >
                    > a=[1]
                    > b=a
                    > a[0]=2
                    > print b
                    >
                    > is another use for 'is'.[/color]

                    Certainly, and there are many other real world use cases for "is",
                    just not for "is" on immutables.

                    Axel

                    Comment

                    • Asun Friere

                      #25
                      Re: Result of ``a is b''

                      axelboldt@yahoo .com (Axel Boldt) wrote in message news:<40200384. 0403170530.57b6 bba4@posting.go ogle.com>...[color=blue]
                      > Why would anybody ever want to
                      > know whether two strings or tupels are internally stored at the same
                      > location, other than to deduce details of the Python implementation?[/color]

                      Most obviously to tell whether they are the same object or not.
                      While this is not an issue with simple strings, have you considered
                      what effect your suggestions would have on classes inheriting from
                      str?

                      For instance I might have a class 'Name', in a names database, which
                      is a specialised string. In this case '==' function looks to the
                      contents of the strings being compared, while 'is' tells me whether
                      these two strings are the same object. Thus "if name0 == name1 and
                      not name0 is name1" will tell me that I am dealing with a duplicate
                      record. Now this might not be the best way to find duplicates in
                      practice, it's simply first thing that popped into my head in response
                      to your question. But I don't think I'm able to anticipate all the
                      ways in which all programmers might want to apply the distinction
                      between equivalence and identity in their programs? Are you?

                      By the way you /have/ written a program in which a large (or at least
                      important) part of the logic was contained in the __eq__ method to the
                      class you created, haven't you? I mean you wouldn't really be in a
                      situation to advocate a redefinition of the identity/equivalence
                      relationship unless you had, would you?

                      Comment

                      • Erik Max Francis

                        #26
                        Re: Result of ``a is b''

                        Axel Boldt wrote:
                        [color=blue]
                        > Lastly, using my redefinition of "is", we have the following nice
                        > property for all objects a and b (mutable or immutable):
                        >
                        > a is b iff in any code block not containing "id()" or "is", any
                        > (or all) occurrances of a can be replaced by b, with
                        > identical results
                        >
                        > In the current implementation, the above equivalence only holds if we
                        > remove "not containing id() or is", and then the statement becomes a
                        > mere tautology without nutritious value.[/color]

                        I'm at a loss to understand why you want to change the behavior of the
                        `is' operator if you aren't clear on what it's used for in the first
                        place.

                        --
                        __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
                        / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
                        \__/ Does the true light / Of love come in flashes
                        -- Sandra St. Victor

                        Comment

                        • David M. Cooke

                          #27
                          Re: Result of ``a is b''

                          At some point, David MacQuigg <dmq@gain.com > wrote:
                          [color=blue]
                          > On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news@ph ysics.mcmaster. ca
                          > (David M. Cooke) wrote:
                          >[color=green]
                          >>Personally, almost all my uses of 'is' are of the form 'x is None' or
                          >>'x is not None'.[/color]
                          >
                          > Here are some more test results (averaging 10,000 evaluations in a
                          > tight loop):
                          >
                          > time (sec) %
                          > Test 1: 3.68E-007 100.0 F is False
                          > Test 2: 4.87E-007 132.1 F == False
                          > Test 3: 3.71E-007 100.0 N is None
                          > Test 4: 5.51E-007 148.6 N == None
                          >
                          > The '== None' test is 49% slower than 'is None', but in absolute time,
                          > the difference is only 180nec (on my new, but not top-speed PC). So
                          > it would take about 10 million of these comparisons in a short time to
                          > make a noticable difference to the user.
                          >
                          > I can't see where the 'is' test would *ever* be needed for the above
                          > comparisons.[/color]

                          I do a lot of stuff with arrays in Numeric, which override __eq__ to
                          elementwise comparision:

                          Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
                          [GCC 3.3.3 (Debian)] on linux2
                          Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
                          >>> import Numeric
                          >>> x = Numeric.array([0,1,2,3])
                          >>> x == None[/color][/color][/color]
                          array([0,0,0,0])[color=blue][color=green][color=darkred]
                          >>> bool(x == None)[/color][/color][/color]
                          False[color=blue][color=green][color=darkred]
                          >>> x is None[/color][/color][/color]
                          False[color=blue][color=green][color=darkred]
                          >>> x == False[/color][/color][/color]
                          array([1,0,0,0])[color=blue][color=green][color=darkred]
                          >>> bool(x == False)[/color][/color][/color]
                          True[color=blue][color=green][color=darkred]
                          >>> x is False[/color][/color][/color]
                          False[color=blue][color=green][color=darkred]
                          >>> bool(x == True)[/color][/color][/color]
                          True[color=blue][color=green][color=darkred]
                          >>> bool(x == True and x == False)[/color][/color][/color]
                          True

                          [Ok, so bool(x == None) returns False, which is good, but imagine the
                          overhead if x was an array of several million elements. x == None
                          would allocate a new array of the same size.]

                          --
                          |>|\/|<
                          /--------------------------------------------------------------------------\
                          |David M. Cooke
                          |cookedm(at)phy sics(dot)mcmast er(dot)ca

                          Comment

                          • Axel Boldt

                            #28
                            Re: Result of ``a is b''

                            afriere@yahoo.c o.uk (Asun Friere) wrote[color=blue]
                            > axelboldt@yahoo .com (Axel Boldt) wrote[/color]
                            [color=blue][color=green]
                            > > Why would anybody ever want to
                            > > know whether two strings or tupels are internally stored at the same
                            > > location, other than to deduce details of the Python implementation?[/color]
                            >
                            > Most obviously to tell whether they are the same object or not.
                            > While this is not an issue with simple strings, have you considered
                            > what effect your suggestions would have on classes inheriting from
                            > str?[/color]

                            Indeed I have not. Probably because basic built-in strings form a type
                            that's not a class and you can't inherit from it.
                            [color=blue]
                            > For instance I might have a class 'Name', in a names database, which
                            > is a specialised string. In this case '==' function looks to the
                            > contents of the strings being compared, while 'is' tells me whether
                            > these two strings are the same object. Thus "if name0 == name1 and
                            > not name0 is name1" will tell me that I am dealing with a duplicate
                            > record.[/color]

                            If you make Name a class that contains a string as a data attribute,
                            then "is" on Name objects will work as always, since Names aren't
                            immutable. To test whether you have duplicates, you can use "is" on
                            Names.

                            Now, rather than test "is" on Name objects, one could be tempted to
                            test "is" on the string attributes instead. Note that sometimes
                            strings created by completely different parts of a program compare as
                            "is-identical". Sometimes they don't, even though they are "==-equal".
                            It's implementation dependent. Name is broken. My proposal would
                            eliminate this very programming mistake.
                            [color=blue]
                            > By the way you /have/ written a program in which a large (or at least
                            > important) part of the logic was contained in the __eq__ method to the
                            > class you created, haven't you?[/color]

                            No.
                            [color=blue]
                            > I mean you wouldn't really be in a
                            > situation to advocate a redefinition of the identity/equivalence
                            > relationship unless you had, would you?[/color]

                            Why not?

                            Axel

                            Comment

                            • DomF

                              #29
                              Re: Result of ``a is b''

                              > Indeed I have not. Probably because basic built-in strings form a type[color=blue]
                              > that's not a class and you can't inherit from it.
                              >[/color]
                              Mostly because I am interested in the counter argument:

                              class mynewstr(str):
                              .... pass
                              ....[color=blue][color=green][color=darkred]
                              >>> s = mynewstr()
                              >>> dir(s)[/color][/color][/color]
                              <<list of str stuff>>


                              Comment

                              • David MacQuigg

                                #30
                                Re: Result of ``a is b''


                                [color=blue]
                                >At some point, David MacQuigg <dmq@gain.com > wrote:[color=green]
                                >> I can't see where the 'is' test would *ever* be needed for the above
                                >> comparisons.[/color]
                                >[/color]
                                On Thu, 18 Mar 2004 01:17:53 -0500, cookedm+news@ph ysics.mcmaster. ca
                                (David M. Cooke) wrote:[color=blue]
                                >I do a lot of stuff with arrays in Numeric, which override __eq__ to
                                >elementwise comparision:
                                >
                                >Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
                                >[GCC 3.3.3 (Debian)] on linux2
                                >Type "help", "copyright" , "credits" or "license" for more information.[color=green][color=darkred]
                                >>>> import Numeric
                                >>>> x = Numeric.array([0,1,2,3])
                                >>>> x == None[/color][/color]
                                >array([0,0,0,0])[color=green][color=darkred]
                                >>>> bool(x == None)[/color][/color]
                                >False[color=green][color=darkred]
                                >>>> x is None[/color][/color]
                                >False[color=green][color=darkred]
                                >>>> x == False[/color][/color]
                                >array([1,0,0,0])[color=green][color=darkred]
                                >>>> bool(x == False)[/color][/color]
                                >True[color=green][color=darkred]
                                >>>> x is False[/color][/color]
                                >False[color=green][color=darkred]
                                >>>> bool(x == True)[/color][/color]
                                >True[color=green][color=darkred]
                                >>>> bool(x == True and x == False)[/color][/color]
                                >True
                                >
                                >[Ok, so bool(x == None) returns False, which is good, but imagine the
                                >overhead if x was an array of several million elements. x == None
                                >would allocate a new array of the same size.][/color]

                                For the rare case where storage of None elements is an issue, could
                                you define your own 'none' object, and simply point all references to
                                it. That would allow you to use 'is', avoiding the overhead of '==',
                                and not mess with the normal definition of '=='. Most importantly, it
                                would allow you to use 'is' with confidence that a Python
                                implementation change, or a move to a new platform, won't trash your
                                program.
                                [color=blue][color=green][color=darkred]
                                >>> class none:[/color][/color][/color]
                                def __repr__(self):
                                return 'none'
                                ... whatever other attributes you need for 'none'
                                [color=blue][color=green][color=darkred]
                                >>> n0 = none()
                                >>> n1 = n2 = n0
                                >>> n1 == n2[/color][/color][/color]
                                True[color=blue][color=green][color=darkred]
                                >>> n1 is n2[/color][/color][/color]
                                True[color=blue][color=green][color=darkred]
                                >>> n1[/color][/color][/color]
                                none[color=blue][color=green][color=darkred]
                                >>>[/color][/color][/color]

                                -- Dave

                                Comment

                                Working...