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
To be clear, you shouldn't do it.
But, you can get at the underlying C data via
ctypesmodule.https://replit.com/@TangibleLight/ctypes-tuple-demo
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_itemarray, and deallocate the oldob_itemarray. 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] 1 points · Jan 2023
Perfect, exactly what I was looking for! Glad the dark arts are this accessible.