tempfile.NamedTemporaryFile use case?

Discussion in 'Python' started by Roy Smith, Dec 31, 2010.

  1. Roy Smith

    Roy Smith Guest

    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.
    Roy Smith, Dec 31, 2010
    1. Advertisements

  2. 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.
    Alice Bevan–McGregor, Dec 31, 2010
    1. Advertisements

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
  2. Lee Harr
    Tim Peters
    Dec 30, 2005
  3. Jason Lunz

    monkeypatching NamedTemporaryFile

    Jason Lunz, May 26, 2006, in forum: Python
    Jason Lunz
    May 27, 2006
  4. Imbaud Pierre

    tempfile.NamedTemporaryFile wont work

    Imbaud Pierre, Nov 19, 2006, in forum: Python
    Imbaud Pierre
    Nov 19, 2006
  5. Alex van der Spek

    Difference between tempfile and spooled tempfile?

    Alex van der Spek, Apr 5, 2012, in forum: Python
    Steve Howell
    Apr 5, 2012

Share This Page