4 ms·
I mean, who says Python strings are immutable? s = "asd" import ctypes ctypes.memmove(id(s) + ord('1'), b'X', 1) print(s) # prints aXd (Python 3.3+, 6
by nneonneo 6y ago
I mean, who says Python strings are immutable?
s = "asd"
import ctypes
ctypes.memmove(id(s) + ord('1'), b'X', 1)
print(s) # prints aXd
(Python 3.3+, 64-bit; this is a joke so please do not use this in anything real)
- yccs27 6y agoNice! Can you please explain to a rookie what the ord('1') is for? Is it just a way of writing a magic number of value 49, or is there some significance to it?
- nneonneo 6y agoIt's mostly just a mildly obfuscated way to write 49. It also happens to line up nicely with the index of the character being overwritten (index 1); ord('0') through ord('9') work likewise. ---- I'm personally kind of shocked at how big strings are - the minimum size is 6 native words in size, corresponding to the following fields: refcount, type pointer, string length, string hash (precomputed), flags, and a wstr pointer which just seems to be NULL for most strings. It seems like they could have at least merged the string length and flags together for short strings - a possible subject for a future PEP...
- rasjani 6y agoIt feels like its just "magic" number. Probably id() is the actual raw pointer to str class and the string starts at offset 48 ?
- panda88888 6y agoCPython implementation of the string stores metadata to save memory. The ord('1') simply jumps to the correct memory offset in the string structure. I would think it's easier to remember ord('0') as the offset of the string byte array in the structure than the magic number 48?
- fireflies_ 6y agoYes, you can can replace that with the magic number 49 if you want, ord('1') == 49 because ord returns the unicode code point for a character. Documentation is here for the curious: https://docs.python.org/3/library/functions.html#ord https://docs.python.org/3/library/functions.html#ord