How to edit immutable objects in cpython?

For example, a tuple. What's the easiest way to delete an item from it?

Obviously you shouldn't, I'm just wondering if there's a way to do it within python or whether it would require editing and recompiling the cpython source code to make tuples mutable.

2 comments · 100% upvoted · other discussions

comments

TangibleLight

To be clear, you shouldn't do it.

But, you can get at the underlying C data via ctypes module.

https://replit.com/@TangibleLight/ctypes-tuple-demo

x = ('x', 'y')
y = ('x', 'y')

ptr = PyTupleObject.from_address(id(x))
ptr.items[1] = 'w'

print(x)           # ('x', 'w')
print(y)           # ('x', 'w')
print(('x', 'y'))  # ('x', 'w')

Note that deleting or adding an item to a tuple is particularly difficult, since you'd need to manage refcounts manually, allocate a new ob_item array, and deallocate the old ob_item array. Very tricky to do correctly, because you really aren't meant to do it at all.

Even the code above is technically incorrect, as I don't properly manage the refcounts of 'y' or 'w'. It doesn't happen to matter here since short strings are interned by CPython, but using a different object might cause problems.

to7m [OP]

Perfect, exactly what I was looking for! Glad the dark arts are this accessible.