1

I have a question about the Python 2.7.5-Python 2.7.13. It may be about semantics or it may be a genuine Python bug. I'm not entirely sure which. Here is the simplest code I can construct with the issue

Python 2.7.13 |Enthought, Inc. (x86_64)| (default, Mar  2 2017, 08:20:50) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin

>>> dd = {'foo': {'yy':u'Tannenbaum'}}

>>> dd['foo']['yy'] is u'Tannenbaum'

False

>>> dd['foo']['yy'] == u'Tannenbaum'

True

Note: If 'Tannebaum' is changed from unicode to a string the outcome changes. Both of the final tests are true. The question is: Why do the two final tests differ in the unicode case? My understanding is that since unicode and strings are both immutables the "is" and "==" tests should never differ in value. But I get this behavior in both Python 2.7.13 and the old 2.7.5 that came installed on my Mac. Am I relying on something I shouldn't rely on? Is the moral that I should never use "is" for string equality? But what is the principle that tells me that?

Postscript: I have access to a Python 3.6.2 on another machine, and lo and behold, I cannot reproduce this anomaly.

Python 3.6.2 (default, Jul 30 2017, 12:03:06) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> dd = {'foo': {'yy':u'Tannenbaum'}}

>>> dd['foo']['yy'] is u'Tannenbaum'
True

>>> dd['foo']['yy'] == u'Tannenbaum'
True
cs95
  • 379,657
  • 97
  • 704
  • 746

0 Answers0