The behavior of what you want to do is nondeterministic. Depending on the implementation and internal functioning of Python (CPython, PyPi, ...), this can be work or not:
Working example:
t = {
'fd': open('data.txt', 'r')
}
def hook_close_fd():
print('del dictionary, close the file')
t['fd'].close = hook_close_fd
del t
Output:
del dictionary, close the file
In this case, the close
function is called on delete
Non working example:
t = {
'fd': open('data.txt', 'r')
}
def hook_close_fd():
print('del dictionary, close the file')
t['fd'].close = hook_close_fd
3 / 0
Output of 1st run:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-211-2d81419599a9> in <module>
10 t['fd'].close = hook_close_fd
11
---> 12 3 / 0
ZeroDivisionError: division by zero
Output of 2nd run:
del dictionary, close the file
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-212-2d81419599a9> in <module>
10 t['fd'].close = hook_close_fd
11
---> 12 3 / 0
ZeroDivisionError: division by zero
As you can see, when an exception is raised, you can't be sure if your file descriptor will be closed properly (especially if you don't catch exception yourself).
close
or awith
statement). Deleting the variable (directly or as part of a dict) isn't really the right way to do it – Arbe