Gary> *Do NOT use "is" to compare immutable types.* **Ever! **

The obvious followup question is then, "when is it ok to use 'is'?"

    Robert> Well, "foo is None" is actually recommended practice....

Indeed.  It does have some (generally small) performance ramifications as
well.  Two trivial one-line examples:

    % python -m timeit -s 'x = None' 'x is None'
    10000000 loops, best of 3: 0.065 usec per loop
    % python -m timeit -s 'x = None' 'x == None'
    10000000 loops, best of 3: 0.121 usec per loop
    % python -m timeit -s 'x = object(); y = object()' 'x == y'
    10000000 loops, best of 3: 0.154 usec per loop
    % python -m timeit -s 'x = object(); y = object()' 'x is y'
    10000000 loops, best of 3: 0.0646 usec per loop

I imagine the distinction grows if you implement a class with __eq__ or
__cmp__ methods, but that would make the examples greater than one line
long.  Of course, the more complex the objects you are comparing the
stronger the recommendation agaist using 'is' to compare two objects.

Skip
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to