tempname.mktemp functionality deprecation

Devin Jeanpierre jeanpierreda at gmail.com
Sat Apr 29 23:51:53 EDT 2017


On Sat, Apr 29, 2017 at 11:45 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
> Unfortunately, tempfile.mktemp() is described as deprecated
> since 2.3 (though appears to still exist in the 3.4.2 that is the
> default Py3 on Debian Stable). While the deprecation notice says
> "In version 2.3 of Python, this module was overhauled for enhanced
> security. It now provides three new functions, NamedTemporaryFile(),
> mkstemp(), and mkdtemp(), which should eliminate all remaining need
> to use the insecure mktemp() function", as best I can tell, all of
> the other functions/objects in the tempfile module return a file
> object, not a string suitable for passing to link().
>
> So which route should I pursue?
>
> - go ahead and use tempfile.mktemp() ignoring the deprecation?
>
> - use a GUID-named temp-file instead for less chance of collision?
>
> - I happen to already have a hash of the file contents, so use
>   the .hexdigest() string as the temp-file name?
>
> - some other solution I've missed?

I vote the last one: you can read the .name attribute of the returned
file(-like) object from NamedTemporaryFile to get a path to a file,
which can be passed to other functions.

I guess ideally, one would use linkat instead of os.link[*], but that's
platform-specific and not exposed in Python AFAIK. Maybe things would
be better if all the functions that accept filenames should also
accept files, and do the best job they can? (if a platform supports
using the fd instead, use that, otherwise use f.name).

.. *: http://stackoverflow.com/questions/17127522/create-a-hard-link-from-a-file-handle-on-unix/18644492#18644492

-- Devin


More information about the Python-list mailing list