monkeypatching NamedTemporaryFile

Discussion in 'Python' started by Jason Lunz, May 26, 2006.

  1. Jason Lunz

    Jason Lunz Guest

    Is there a better way to do this?

    def QuietNamedTemporaryFile(**kwargs):

    '''
    Return a NamedTemporaryFile that doesn't complain when its file has already
    been unlinked at __del__ time.
    '''

    tf = tempfile.NamedTemporaryFile(**kwargs)

    def quiet_del():
    try:
    tf.close()
    except OSError:
    pass

    tf.__del__ = quiet_del

    return tf

    Jason
    Jason Lunz, May 26, 2006
    #1
    1. Advertising

  2. Jason Lunz

    Guest

    Maybe that should be the default behaviour. Presumably the file has
    been deleted by some other process?
    , May 27, 2006
    #2
    1. Advertising

  3. Jason Lunz

    Jason Lunz Guest

    said:
    > Maybe that should be the default behaviour. Presumably the file has
    > been deleted by some other process?


    The use case is that a NamedTemporaryFile was used to securely create
    and populate a file, which is then atomically (on posix) os.rename()d to
    its final location.

    If any error occurs prior to the rename, NamedTemporaryFile takes care
    of deleting the tempfile on the error path. But in the success case,
    NamedTemporaryFile causes an unsightly "ignored exception" message on
    stderr when it fails to unlink the now-nonexistent tempfile.

    Jason
    Jason Lunz, May 27, 2006
    #3
    1. Advertising

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:
    1
    Views:
    304
  2. Nikolaus Rath

    Monkeypatching an object to become callable

    Nikolaus Rath, Aug 9, 2009, in forum: Python
    Replies:
    6
    Views:
    284
    Gabriel Genellina
    Aug 13, 2009
  3. Avdi Grimm

    Monkeypatching is Destroying Ruby

    Avdi Grimm, Feb 23, 2008, in forum: Ruby
    Replies:
    115
    Views:
    856
    Clifford Heath
    Mar 8, 2008
  4. Replies:
    2
    Views:
    92
    Phlip
    Feb 25, 2008
  5. Trans
    Replies:
    1
    Views:
    80
    s.ross
    Feb 28, 2008
Loading...

Share This Page