destructor

PyBind11 destructor not invoked?

PyBind11 destructor not invoked? Question: I have a c++ class wrapped with PyBind11. The issue is: when the Python script ends the c++ destructor is not being automatically invoked. This causes an untidy exit because networking resources need to be released by the destructor. As a work-around it is necessary to explicitly delete the Python …

Total answers: 3

Why is __del__ not called on a global object when another thread is active?

Why is __del__ not called on a global object when another thread is active? Question: I am working on a project that has a similar construct to that shown in the code below. My hope is to have an object that opens a thread upon creation and automatically closes it when the object is destroyed. …

Total answers: 3

Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

Python __enter__ / __exit__ vs __init__ (or __new__) / __del__ Question: I have searched and I’m unable to come up with any good reason to use python’s __enter__ /__exit__ rather than __init__ (or __new__ ?) / __del__ . I understand that __enter__ / __exit__ are intended for use with the with statement as context managers, …

Total answers: 3

Determine if python is exiting

Determine if python is exiting Question: Is there a way to determine if python is shutting down? Basically: def Foo(object): def __del__(self): if PYTHON_IS_EXITING: do_this else: do_that foo1 = Foo() del foo1 # calls do_that foo2 # calls do_this when python exits The context is multiprocessing.ThreadPool doesn’t work when python is exiting and do_that will …

Total answers: 3

Right way to clean up a temporary folder in Python class

Right way to clean up a temporary folder in Python class Question: I am creating a class in which I want to generate a temporary workspace of folders that will persist for the life of the object and then be removed. I am using tempfile.mkdtemp() in the def __init__ to create the space, but I …

Total answers: 6

How to force deletion of a python object?

How to force deletion of a python object? Question: I am curious about the details of __del__ in python, when and why it should be used and what it shouldn’t be used for. I’ve learned the hard way that it is not really like what one would naively expected from a destructor, in that it …

Total answers: 4

How do I correctly clean up a Python object?

How do I correctly clean up a Python object? Question: class Package: def __init__(self): self.files = [] # … def __del__(self): for file in self.files: os.unlink(file) __del__(self) above fails with an AttributeError exception. I understand Python doesn’t guarantee the existence of “global variables” (member data in this context?) when __del__() is invoked. If that is …

Total answers: 11