Python's tempfile.unlink() needs a single parameter, the name of the entity to unlink. As this is known to the object/class, and the method is otherwise undocumented in tempfile, IMHO it seems it should take only it's own filename to unlink.
It also seems odd to allow the unlink method on one object to delete any arbitrary file.
Or are there other use cases I've missed?
Quantum@Mechanic:/tmp$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> x = tempfile.NamedTemporaryFile(delete=False)
>>> x.name
'/tmp/tmp_It8iM'
>>> x.close()
>>> x.unlink()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly 1 argument (0 given)
>>> x.unlink(x.name)
>>>
Digging into the source code:
import os as _os
unlink = _os.unlink
What you have discovered is an accident of implementation. There is no documented NamedTemporaryFile.unlink
method, but as you've seen one does seem to exist. Specifically it is the same as os.unlink
, and you should never call it yourself, because it is an undocumented (mis)feature.
If you want to see the implementation, which actually has a comment about why the unlink()
method exists (but not exactly why it has to have that confusing name), see here: https://github.com/python-git/python/blob/master/Lib/tempfile.py#L387
# NT provides delete-on-close as a primitive, so we don't need
# the wrapper to do anything special. We still use it so that
# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
if _os.name != 'nt':
# Cache the unlinker so we don't get spurious errors at
# shutdown when the module-level "os" is None'd out. Note
# that this must be referenced as self.unlink, because the
# name TemporaryFileWrapper may also get None'd out before
# __del__ is called.
unlink = _os.unlink
If you want to delete what you created with tempfile.NamedTemporaryFile(delete=False)
, do it this way:
x.close()
os.unlink(x.name)
This avoids depending on implementation details which may change in the future.