Tuesday, November 25, 2014

ctypes short string shenannigans


>>>
>>>
>>>
42105668
>>>
42105668
>>>
'f'
>>>
'ab'
>>>
'f'
import ctypes
b_char = 'b'
ctypes.pythonapi.PyString_AsString(id(b_char))

ctypes.memset(_, ord('f'), 1)


b_char


'ab'


'ab'[1:]



Single character strings are interned in a special array in CPython.  This means mutation to the internals of a single character string will have global consequences.

(http://www.laurentluce.com/posts/python-string-objects-implementation/ has more information.)

No comments:

Post a Comment