[Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?
robertvstepp at gmail.com
Mon Oct 22 10:24:34 EDT 2018
Forwarding to the Tutor list. Herr Maier offers a good idea that
would take away much of a remaining issue -- the name "Temporary". I
need to look into the functools library to see what "partial" does.
---------- Forwarded message ---------
From: Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de>
Date: Mon, Oct 22, 2018 at 5:25 AM
Subject: Re: Can tempfile.NamedTemporaryFile(delete=False) be used to
create *permanent* uniquely named files?
To: boB Stepp <robertvstepp at gmail.com>
On 21.10.18 08:13, boB Stepp wrote:
> Use case: I want to allow a user of my Solitaire Scorekeeper program
> to be able to give any name he wants to each game of solitaire he
> wishes to record. My thought for permanent storage of each game's
> parameters is to use a dictionary to map the user-chosen game names to
> a unique json filename. This way I hope no shenanigans can occur with
> weird characters/non-printing characters.
> My initial thought was to just have a sequence of game names with
> incrementing numerical suffixes: game_0, game_1, ... , game_n. But
> this would require the program to keep track of what the next
> available numerical suffix is. Additionally, if a user chooses to
> delete a game, then there would be a gap in the numerical sequence of
> the game filenames. I find such a gap aesthetically displeasing and
> would probably go to additional efforts to reuse such deleted
> filenames, so there would be no such "gaps".
> So I am now wondering if using
> tempfile.NamedTemporaryFile(delete=False) would solve this problem
> nicely? As I am not very familiar with this library, are there any
> unforeseen issues I should be made aware of? Would this work equally
> well on all operating systems?
This sounds like a good though surprising use case. The only odd thing
about this is the misleading name then of the function, plus there is
the (vague) possibility that the stdlib module might evolve and no
longer support this undocumented (given that the first sentence in the
module description reads: "This module creates temporary files and
directories.") use case.
I would probably address these issues and the handling of the dir
parameter via a partial function like this:
from functools import partial
SavedGameFile = partial(
) # if you like also set the suffix here
SavedGameFile.__doc__ = """\
Create and return a saved game file, ...
This way you have a good name for the function, and you can redefine the
function, if you ever want/need to move away from NamedTemporaryFile,
without having to rewrite every function call.
More information about the Tutor