[issue45833] NamedTemporaryFile deleted before enclosing context manager exit

Zachary Ware report at bugs.python.org
Wed Nov 17 17:58:01 EST 2021


Zachary Ware <zachary.ware at gmail.com> added the comment:

It's a bit convoluted, but the file is actually deleted before the `os.stat` call.  Because there are no references to anything but the `name` (which is just a string), the `_GeneratorContextManager` (result of `my_tmp_file`) and the `_TemporaryFileWrapper` (result of `my_tmp_file().__enter__()`) are both destroyed.  Because `NamedTemporaryFile` is called with `delete=True` (default), the `_TemporaryFileWrapper` has a `_closer` attribute which is a `_TemporaryFileCloser`, which calls `self.close()` in `__del__`, which deletes the file.

If a reference to the result of `my_tmp_file()` is saved anywhere along the way, none of the objects are destroyed and the file still exists.  This also wouldn't happen in an implementation without reference counting.

----------
nosy: +zach.ware
resolution:  -> not a bug
status: open -> pending

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45833>
_______________________________________


More information about the Python-bugs-list mailing list