import gc def func(): class TestException(MemoryError): pass try: raise MemoryError except MemoryError as exc: inst = exc # inst = first preallocated MemoryError try: raise TestException except Exception: pass inst = None try: raise MemoryError except MemoryError as exc: pass gc.collect() if __name__ == "__main__": func() print("ok")