Strange behavior when comparing unicode objects with string objects

python, python-2.7, unicode

Solution

Don't use `is` for this, use `==`. You're comparing whether the objects have the same identity, not whether they are equal. Of course, if the are the same object, they will be equal (`==`), but if they are equal, they aren't necessarily the same object.

The fact that the first one works is an implementation detail of CPython. Small strings, since they're immutable can be interned by the interpreter. Every time you put the string `"s"` in your source code, Cpython reuses the same object. however, apparently `str("s")` returns a new string with the same value. This isn't all that surprising.

You might be asking yourself, "why intern the string `'s'` at all?". That's a reasonable question. After all, it's a short string -- How much memory could having multiple copies floating around in your source take? The answer (I think) is because of dictionary lookups. Since dicts with strings as keys are so common in python, you can speed up the hash function/equality checking of keys by doing lightning fast pointer comparisons (falling back on slower `strcmp`) when the pointer comparison returns false.

Problem

when comparing two strings in python, it works fine and when comparing a `string` object with a `unicode` object it fails as expected however when comparing a `string` object with a converted unicode `(unicode --> str)` object it fails A Demo: Works as expected: ``` >>> if 's' is 's': print "Hurrah!" ... Hurrah! ``` Pretty much yeah: ``` >>> if 's' is u's': print "Hurrah!" ... ``` Not expected: ``` >>> if 's' is str(u's'): print "Hurrah!" ... ``` Why doesn't the third example work as expected when both the type's are of the same class? ``` >>> type('s') <type 'str'> >>> type(str(u's')) <type 'str'> ```

Original source

Related problems