Jython class names
mcherm at mcherm.com
Tue Sep 9 14:19:52 CEST 2003
Robin Becker writes:
> [...] Is the above test robust or should
> I always be using == for testing class names?
Simple rule. ALWAYS use "==" for comparing strings, NEVER use "is". The
only exception is if you are working on the internals of the string
class, or perhaps writing some subclass of string with wierd behavior.
The behavior of "is" is undefined for all immutable built-in types --
not "undefined behavior" in the sense of the C standard (computer may
grow legs and wander out of the room if you do this), but "undefined"
in the sense that comparing two integers or two strings with "is" MAY
return True, or it may return False, and no promises are made as to
which way it will go.
By the way, Java has the exact same issue... in Java you should ALWAYS
compare Strings using ".equals()" instead of "==", or the behavior is
undefined. Unfortunately, in Java, you have to remember to use the
awkward syntax ("a.equals(b)") instead of the simple syntax ("a == b"),
while in Python you just use the simple syntax ("a == b") instead of
having to remember to use the special syntax ("a is b").
Actually, there are very few good reasons to use "is" in Python. Being
minutely faster is _NOT_ a good reason (show me a real program where
THAT kind of optimization has any measurable effect!). Convention is
a half-way decent reason ("x is None" is often preferred over "x == None").
But you'll hardly ever go wrong by using "==" instead of "is".
-- Michael Chermside
More information about the Python-list