[Python-Dev] Remove tempfile.mktemp()

Sebastian Rittau srittau at rittau.biz
Tue Mar 19 10:12:06 EDT 2019


Am 19.03.19 um 14:53 schrieb Victor Stinner:
>
> When I write tests, I don't really care of security, but
> NamedTemporaryFile caused me many troubles on Windows: you cannot
> delete a file if it's still open in a another program. It's way more
> convenient to use tempfile.mktemp().
>
> O_EXCL, open(tmpname, "wx"), os.open(tmpname, os.O_CREAT | os.O_EXCL |
> os.O_WRONLY), etc. can be used to get an error if the file already
> exists.
>
> I agree that for production code where security matters,
> tempfile.mktemp() must be avoided. But I would prefer to keep it for
> tests.

If there are valid use cases for mktemp(), I recommend renaming
it to mkname_unsafe() or something equally obvious. Experience
(and the list of packages still using mktemp() posted here) shows
that just adding a warning to documentation is not enough. Users
often discover functions by experimentation or looking at examples
on the internet.

mktemp() is also unfortunately named, as it does not create a temp
file as implied. This can also add to the impression that it is the
proper function to use.

Adding a new function and following the deprecation process for the
old one should only be a minor inconvenience for existing users that
need it, should wake up existing users that should not use it in the
first place, and still allows it to be used for relevant use cases.

I believe for security reasons sometimes inconvenient changes like
this are necessary.

  - Sebastian



More information about the Python-Dev mailing list