Result of ``a is b''

Skip Montanaro skip at pobox.com
Tue Mar 16 16:23:03 EST 2004


>>>>> "Axel" == Axel Boldt <axelboldt at yahoo.com> writes:

    Axel> David MacQuigg <dmq at gain.com> wrote 
    >> >>> x = 'akdijfkdienlskfi'
    >> >>> y = 'akdijfkdienlskfi'
    >> >>> x is y
    >> True
    >> >>> x = 'a b'
    >> >>> y = 'a b'
    >> >>> x is y
    >> False

    Axel> Wow. So it seems that the action of "is" on immutables is
    Axel> unspecified and implementation dependent, thus useless to the
    Axel> programmer.

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.

Note that even though I "know" that small integers, identifier-like strings
and the null tuple are all shared objects, the language implementation is
free to change.  Those are simply optimizations which you can't rely on.
Use "==" when comparing integers, strings and tuples.

Trying to use "is" when you want a performance improvement is generally
unwise.  There is a performance hit going from "is" to "==", but it's
probably going be down in the noise compared to all the other things a
significant program needs to do.  Ordered from fastest to slowest, timing a
pass statement, "a is b", "a == b" and a call to a function that only
executes a pass statement:

    % timeit.py -s "a = b = 'frankie and johnny'" "pass"
    10000000 loops, best of 3: 0.132 usec per loop
    % timeit.py -s "a = b = 'frankie and johnny'" "a is b"
    1000000 loops, best of 3: 0.372 usec per loop
    % timeit.py -s "a = b = 'frankie and johnny'" "a == b"
    1000000 loops, best of 3: 0.491 usec per loop
    % timeit.py -s "def f(): pass" "f()"
    1000000 loops, best of 3: 1.1 usec per loop

"a == b" is still twice as fast as a null function call.

Moral of the story: stop writing code that contains so many
functions. <wink>

Skip




More information about the Python-list mailing list