[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Sticky Variables: Terrain Loading
On Mar 12, 2008, at 7:54 AM, kschnee wrote:
long1 = "water is wet"
long2 = "water is wet"
long1 is long2
False
short1 = "water"
short2 = "water"
short1 is short2
True
This really surprises me! I hadn't known about these automatic
optimizations. Yes, I know that "== != is", but the rest of it is
news to
me.
Python caches short string values (which must not contain a space) as
an optimization under the assumption that they will be referenced
repeated (such as for dict keys, which are used often internally by
the python interpreter). Since short strings without spaces are often
python identifiers, and referenced very often.
This is an implementation detail of the CPython interpreter (as is the
reuse of integer objects) which should be of little or no consequence
to python programs. You should not rely on identity values (e.g.,
id('foo') or 'foo' is 'foo') for strings, integers and other
"primitive" types since the interpreter my arbitrarily use singletons
to represent some values. IOW using the "is" keyword for strings,
integers, floats, etc. is not useful and potentially confusing. To
compare these values for equality, only use ==.
"is" is typically useful only for class instances and certain special
objects like None. Note that:
a is b
is equivalent to (though much faster than):
id(a) == id(b)
-Casey