[Tutor] Object destruction

Roel Schroeven roel at roelschroeven.net
Tue May 24 19:41:05 EDT 2022


Dimitar Ivanov schreef op 24/05/2022 om 15:27:
> It seems like the Finalizer is only kicking off the objects' finalize
> methods once the program exits, which, if I'm reading the documentation
> right, is the correct behaviour; however, I need that finalize method
> kicked off as soon as any reference to those objects is removed. Can I
> achieve that in any way?

I get the feeling that you are trying to achieve something like RAII 
("Resource acquisition is initialization") in C++. Is that correct? In 
C++ it's indeed possible, and the recommend way of doing things, to do 
finalization in the destructor which in C++ is closely tied to the 
object's scope.

In Python things work differently. The recommended way to handle 
resource management is through context managers (with 'with' 
statements). Many of the built-in classes provide context managers, as 
in this example:

     with open('hello.txt', 'r') as f:
         for line in f:
             ...

The file is automatically closed after the 'with' statement, or when an 
exception is raised. You can create context managers for your own 
classes, too. See e.g. 
https://betterprogramming.pub/everything-you-need-to-know-about-context-managers-in-python-f83556fbdfb

-- 

"Your scientists were so preoccupied with whether they could, they didn't
stop to think if they should"
         -- Dr. Ian Malcolm



More information about the Tutor mailing list