tempfile.NamedTemporaryFile use case?

R

Roy Smith

What is the use case for tempfile.NamedTemporaryFile? As far as I can
tell, the only way it differs from TemporaryFile is that it is
guaranteed to have a name in the file system. BUT, it's not guaranteed
that you can open the file a second time via that name.

So, what's the point? In what situations would NamedTemporaryFile do
what you want but TemporaryFile not?

I'm writing a unit test where I want to verify operation of my code on a
path which can't be opened (i.e. that it raises IOError).
NamedTemporaryFile almost gives me what I want. It creates a file,
tells me what the path is (so I can os.chmod() it to mode 0), and cleans
it up when I'm done (so I don't have to write my own context manager or
whatever). But, it's not guaranteed that I can open the path, so the
whole test is moot.

I can work around that (plain old mktemp() or mkstemp() and have my
tearDown() method do the cleanup), but the more I look at this, the more
I'm scratching my head why NamedTemporaryFile exists.
 
A

Alice Bevan–McGregor

I'm a bad person, but one use case I have is for shuffling templates
around such that:

* An inherited ('parent') template can be stored in a database.
* The 'views' of my application are told to either use the real master
template or the db parent template.
* The rendering engine loads the parent from disk.

Thus I create a NamedTemporaryFile (with some custom prefix and suffix
stuff), write the parent template from DB to it, flush, then let the
rendering engine do its thing. Works like a hot damn, and lets the
users of my CMS manage custom layouts from within the CMS.

Templates are cached using the CMS template path as the dict key, and a
2-tuple of modification time and the NamedTemporaryFile as the value.
Cleanup of old versions on-disk is simple: just close the file!

- Alice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top