Is there a way to globally trap MemoryError exceptions so that a library can clear out caches instead of letting a MemoryError be seen by user code?
I'm developing a memory caching library in Python that stores very large objects, to the point where it's common for users to want to use all available RAM to simplify their scripts and/or speed them up. I'd like to be able to have a hook where the python interpreter asks a callback function to release some RAM as a way of avoiding a MemoryError being invoked in user code.
OS: Solaris and/or Linux
Python: cPython 2.6.*
EDIT: I'm looking for a mechanism that wouldn't be handled by an except block. If there would be a memory error in any code for any reason, I'd like to have the Python interpreter first try to use a callback to release some RAM and never have the MemoryError exception ever generated. I don't control the code that would generate the errors and I'd like my cache to be able to aggressively use as much RAM as it wants, automatically freeing up RAM as it's needed by the user code.