'Open *filepath* for writing in a race condition-free way
(hopefully).'

@contextlib.contextmanager
def _open_for_write(self, filepath):

    tmpname = ('%s.tmp.%d' % (filepath, os.getpid()))
    try:
        with open(tmpname, 'wb') as f:
            (yield f)
        utils.file_replace(tmpname, filepath)
    except Exception:
        try:
            os.unlink(tmpname)
        except OSError:
            pass
        raise
