Seemingly odd 'is' comparison.

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

    Seemingly odd 'is' comparison.

    >>print float(3.0) is float(3.0)
    True
    >>print float(3.0 * 1.0) is float(3.0)
    False
    >>>

    Thanks,

    Tobiah

    --
    Posted via a free Usenet account from http://www.teranews.com

  • Arnaud Delobelle

    #2
    Re: Seemingly odd 'is' comparison.

    On Feb 13, 10:19 pm, Tobiah <t...@tobiah.or gwrote:
    >print float(3.0) is float(3.0)
    True
    >print float(3.0 * 1.0) is float(3.0)
    False
    [You don't need to wrap your floats in float()]
    >>def f():
    ... return 3.0 is 3.0, 3.0*1.0 is 3.0
    ...
    >>f()
    (True, False)
    >>import dis
    >>dis.dis(f)
    2 0 LOAD_CONST 1 (3.0)
    3 LOAD_CONST 1 (3.0)
    6 COMPARE_OP 8 (is)
    9 LOAD_CONST 3 (3.0)
    12 LOAD_CONST 1 (3.0)
    15 COMPARE_OP 8 (is)
    18 BUILD_TUPLE 2
    21 RETURN_VALUE

    As you can see when "3.0 is 3.0" is evaluated the same float object is
    put on the stack twice so the 'is' comparison is True (LOAD_CONST 1 /
    LOAD_CONST 1 / COMPARE_OP 8).

    Whereas when "3.0*1.0 is 3.0" is evaluated, *two* different float
    objects are put on the stack and compared (LOAD_CONST 3 / LOAD_CONST
    1 / COMPARE_OP 8). Therefore the result is False.

    HTH

    --
    Arnaud

    Comment

    • Christian Heimes

      #3
      Re: Seemingly odd 'is' comparison.

      Tobiah wrote:
      >>>print float(3.0) is float(3.0)
      True
      >>>print float(3.0 * 1.0) is float(3.0)
      False
      >>>>
      Thumb rule: Never compare strings, numbers or tuples with "is". Only
      compare an object with a singleton like a type or None. "is" is not a
      comparison operator.

      Christian

      Comment

      • Erik Max Francis

        #4
        Re: Seemingly odd 'is' comparison.

        Tobiah wrote:
        >>>print float(3.0) is float(3.0)
        True
        >>>print float(3.0 * 1.0) is float(3.0)
        False
        >>>>
        It's implementation dependent what values these expressions will take.

        If you're trying to test equality, use `==`, not `is`.

        --
        Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
        San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
        There is nothing more incomprehensibl e than a wrangle among
        astronomers. -- H.L. Mencken

        Comment

        • Asun Friere

          #5
          Re: Seemingly odd 'is' comparison.

          On Feb 19, 12:27 pm, Asun Friere <afri...@yahoo. co.ukwrote:
          But given the nature of immutables
          I meant to write "given the nature of mutables" of course ... :/

          Comment

          Working...