how to prevent Python garbage collection for anony

2019-08-28 02:51发布

问题:

In this Python code

import gc
gc.disable()
<some code ...>
MyClass()
<more code...>

I am hoping that the anonymous object created by MyClass constructor would not be garbage-collected. MyClass actually links to a shared object library of C++ code, and there through raw memory pointers I am able to inspect the contents of the anonymous object.

I can then see that the object is immediately corrupted (garbage collected).

How to prevent Python garbage collection for everything?

I have to keep this call anonymous. I cannot change the part of the code MyClass() - it has to be kept as is.

MyClass() has to be kept as is, because it is an exact translation from C++ (by way of SWIG) and the two should be identical for the benefit of people who translate.

I have to prevent the garbage collection by some "initialization code", that is only called once at the beginning of the program. I cannot touch anything after that.

回答1:

The "garbage collector" referred to in gc is only used for resolving circular references. In Python (at least in the main C implementation, CPython) the main method of memory management is reference counting. In your code, the result of MyClass() has no references, so will always be disposed immediately. There's no way of preventing that.

What is not clear, even with your edit, is why you can't simply assign it to something? If the target audience is "people who translate", those people can presumably read, so write a comment explaining why you're doing the assignment.