Forcefully deallocating objects

suggest change

You can force deallocate objects even if their refcount isn’t 0 in both Python 2 and 3.

Both versions use the ctypes module to do so.

WARNING: doing this will leave your Python environment unstable and prone to crashing without a traceback! Using this method could also introduce security problems (quite unlikely) Only deallocate objects you’re sure you’ll never reference again. Ever.

import ctypes
deallocated = 12345
ctypes.pythonapi._Py_Dealloc(ctypes.py_object(deallocated))
import ctypes, sys
deallocated = 12345
(ctypes.c_char * sys.getsizeof(deallocated)).from_address(id(deallocated))[:4] = '\x00' * 4

After running, any reference to the now deallocated object will cause Python to either produce undefined behavior or crash - without a traceback. There was probably a reason why the garbage collector didn’t remove that object…

If you deallocate None, you get a special message - Fatal Python error: deallocating None before crashing.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents