Sample code: ``` import os from tempfile import TemporaryDirectory name = TemporaryDirectory().name print(os.path.exists(name)) # prints False td = TemporaryDirectory() name_2 = td.name print(os.path.exists(name_2)) # prints True ``` Expected behavior: `True` is printed for both print statements. I have run this example on: * CPython 3.6.3 * CPython 3.5.3 * pypy 3.5.3 The unexpected behavior occurs on CPython 3.5.3 and CPython 3.6.X but not on pypy. (bug found with Tim Weidner https://github.com/timaa2k).
> The unexpected behavior occurs on CPython 3.5.3 and CPython 3.6.X but not on pypy. This suggests that it is something to do with garbage collection. Upon further thought, maybe this is by design, but I still was surprised.
This is by design. The first TemporaryDirectory object is destroyed before the first print statement. For not be surprised use TemporaryDirectory with the "with" statement. with TemporaryDirectory() as td: name = td.name print(os.path.exists(name)) # prints True print(os.path.exists(name)) # prints False
The documentation says “On . . . destruction of the temporary directory object the newly created temporary directory and all its contents are removed”. If you had enabled warnings, you may have seen a hint: $ python -Wdefault -c 'import tempfile; print(tempfile.TemporaryDirectory().name)' /usr/lib/python3.5/tempfile.py:788: ResourceWarning: Implicitly cleaning up <TemporaryDirectory '/tmp/tmpj6100h57'> _warnings.warn(warn_message, ResourceWarning) /tmp/tmpj6100h57 This is similar in spirit to earlier bug reports where workarounds were added, but to avoid this instance of the problem the string object returned by the “name” attribute would have to hold a reference back to the directory object. * Issue 23700: iter(NamedTemporaryFile()) * Issue 18879: NamedTemporaryFile().write(...)