Jython class names

Michael Chermside mcherm at mcherm.com
Tue Sep 9 12:38:28 EDT 2003


Peter Otten writes:
> That's definitely not what I expected. So == is the way to go.
> Still, I'm curious: would the code below return 100 in Jython?
> 
> >>> class C: pass
> ...
> >>> many = [C() for i in range(100)]
> >>> d = {}
> >>> for c in many:
> ...     d[id(c.__class__.__name__)] = None
> ...
> >>> len(d.keys())
> 1

Well, I fired up my Jython and tried it:

Jython 2.1 on java1.3.1_03 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> class C: pass
...
>>> many = [C() for i in range(100)]
>>> d = {}
>>> for c in many:
...     d[id(c.__class__.__name__)] = None
...
>>> len(d.keys())
100
>>>

Apparently the answer is "No". Really, in cPython or Jython or Pippi or
PythonDotNet, or PyPy, or any other python implementation that I may
not have thought of, the rule is that two equivalent strings _WILL_ 
return 1 (or True) if you compare them using "==". But if you compare 
using "is", or compare their "id()"'s, then they _might_ match or
they might not... it's up to the implementation and depends on what
kinds of optimization are done. The same is true for other built-in
immutable types, like int and float.

For example, in cPython 2.3, we get the following:
Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 is 10 - 1
True
>>> 99 is 100 - 1
True
>>> 999 is 1000 - 1
False

This is due to special optimization being provided for small ints.
There's a similar optimization for small strings:
>>> 'a' is 'a' * 1
True
>>> 'aa' is 'a' * 2
False

But if I try both of these in Jython:

Jython 2.1 on java1.3.1_03 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> 9 is 10-1
1
>>> 99 is 100 - 1
1
>>> 999 is 1000 - 1
0
>>> 'a' is 'a' * 1
0
>>> 'aa' is 'a' * 2
0

Apparently that version of Jython includes the same small int optimization
but lacks the small string optimization. Really, if you want the answer
to be reliable, use "==" instead of "is" for immutables.


-- Michael Chermside






More information about the Python-list mailing list