Welcome, guest | Sign In | My Account | Store | Cart

"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[4] = " "
p[5] = " "
print s

Useful to change few chars in a big string without create a new one. ¿Dangerous?

2 comments

Gabriel Genellina 14 years, 2 months ago  # | flag

Absolutely dangerous! :)

py> class X:
...   def __init__(self, foo):
...     self.foo = foo
...
py> x = X(123)
py> x.foo
123
py> p = cast(c_char_p("foo"),POINTER(c_char))
py> p[0] = "b"
py> p[1] = "a"
py> p[2] = "r"
py> x.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: X instance has no attribute 'foo'
py> dir(x)
['__doc__', '__init__', '__module__', 'bar']
py> x.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: X instance has no attribute 'bar'

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.

Pepe Aracil (author) 14 years, 2 months ago  # | flag

Hi, Gabriel.

Excellent explanation!! Thanks.

Created by Pepe Aracil on Mon, 11 Jan 2010 (MIT)
Python recipes (4591)
Pepe Aracil's recipes (2)

Required Modules

Other Information and Tasks