G
G
germn2014-01-24 22:11:37
Python
germn, 2014-01-24 22:11:37

How in Python to ensure that the destructor code is called immediately after the instance is not needed?

As you know, there is no guarantee that __del__ will be called immediately after the object has no references left. But sometimes you want the resources used by an object to be freed immediately when the object is no longer needed. How to guarantee it?
Let's say we have a code:

def test()
    a = Processor('file.txt')
    a.process()

test()
test()

A file is opened in the Processor constructor, the file must be closed in the destructor as soon as the object is no longer needed, that is, immediately after exiting the test() function. If I understand correctly, in theory it may turn out that after the first test () the destructor will not be called, which means that by the second test () we will try to open a file that is not closed.
How to avoid it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2014-01-24
@germn

You need to add functionality to the ContextManager in order to be able to use the class with the with construct. See PEP 343 .

K
Konstantin Dovnar, 2014-01-24
@SolidlSnake

And what prevents at the end of the function to add an explicit closure?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question