x is y
is really checking id(x) is id(y)
, i.e. do those two references point to the same object. str
in CPython will return the same object if it is already a string, so from that perspective the behaviour you describe:
y = str(x)
assert x is y
will work for all x
where isinstance(x, str)
. From the documentation:
For strings, [str
] returns the string itself.
I'm not sure I would consider this a guarantee so much an implementation detail, though, and would try to avoid writing code that relied on it.
There are numerous resources on SO and elsewhere on implementing immutable custom classes in Python, so I will not repeat that information here.