"Useless" alteration of immutable string object in 100% pure python. :)
Python, 6 lines
1 2 3 4 5 6
from ctypes import * s = "I'm immutable" p = cast(c_char_p(s),POINTER(c_char)) p = " " p = " " print s
Useful to change few chars in a big string without create a new one. ¿Dangerous?
Absolutely dangerous! :)
Note that I didn't ask specifically for the "foo" used as an X attribute, I just altered any "foo". And now, x.foo is completely unreachable - dir() says its name is "bar", but x.bar doesn't work [because this bar is in the wrong slot in the dictionary]
You might alter a string only if its reference count is 1 - meaning that it's not shared with anyone else. And only before its hash value has been computed.
Excellent explanation!! Thanks.