'==' vs. 'is' behavior

Tim Peters tim_one at email.msn.com
Tue Nov 30 01:59:52 EST 1999


[François Pinard]
> By the way, is there common wisdom (or rather, maybe,
> usage-standards-to-be) about using `is' instead of `=='?

In general, don't -- you'll often end up regretting this cleverness.  Note
that

    a is b

is the same as

    id(a) == id(b)

so the former is *appropriate* only when the latter is *intended*.  A good
example of appropriate use is in copy.deepcopy, where Python's by-value ==
is useless for determining whether a structure contains a cycle.  A terrible
example is "if i is 42":  whether that appears to work is an accident that
may change from release to release or even run to run.

That said, a few objects are guaranteed to exist uniquely, and so it's OK
(but dubious anyway) to use "is" with them.  "x is None", "x is
types.StringType" (and friends), sometimes "x.__class__ is MyClass", and "s
is t" where it's *known* that s and t are both intern()ed strings.

BTW, the truth of "x is y" implies the truth of "x == y", because the first
thing the (current) implementation of comparison does is check for pointer
equality.  However, "x == y" does not imply "x is y".

Clearest and safest:  don't use "is" when "==" would suffice.

Most pragmatic:  don't use "is" unless you know you can get away with it
forever.

Most common:  use "is" randomly, then complain about suspected Python bugs
at 3 in the morning <0.9 wink>.

x-is-y-is-y-is-x-is-not-x-is-not-y-is-not-y-is-not-x-ly y'rs  - tim






More information about the Python-list mailing list