[Python-ideas] Add create mode to open()

Guido van Rossum guido at python.org
Wed Aug 17 03:11:38 CEST 2011

On Tue, Aug 16, 2011 at 5:08 PM, Mike Meyer <mwm at mired.org> wrote:
> On Tue, Aug 16, 2011 at 4:46 PM, Guido van Rossum <guido at python.org> wrote:
>> On Tue, Aug 16, 2011 at 4:18 PM, Bruce Leban <bruce at leapyear.org> wrote:
>> > On Tue, Aug 16, 2011 at 3:43 PM, Guido van Rossum <guido at python.org>
>> > wrote:
>> >>
>> >> Agreed. Also I think that in most cases the right thing to do is to
>> >> quietly overwrite the file. If you're implementing a UI where you want
>> >> look-before-you-leap, the app should code an explicit test so it can
>> >> issue a proper error message (the exception will not be fun for the
>> >> user :-).
>> >>
>> > This isn't look before you leap. It's catching a failure when the file
>> > can't
>> > be created, just as you would if you don't have permission to write a
>> > file
>> > in that directory or the file already exists and is locked so you don't
>> > have
>> > permission to overwrite it. It just adds one more reason the file can't
>> > be
>> > written.
>> So what's the use case? In general when using a command line
>> environment overwriting the file is what you *want* to happen. Like
>> with Unix "foo >bar". I don't even think there *is* a shell syntax for
>> not overwriting an existing file, though you can use >> to append
>> instead of overwrite -- this is open(filename, 'a').
> The use case is for dealing with precious files. Normally, you deal with
> this stuff with locks to make sure things are safe.  The shell method of
> doing this is to set the noclobber option (bash, csh, probably others).
> Given that the use case is precious files, it should be 100% safe on every
> major platform, and should throw an exception on any platform that doesn't
> have a 100% safe implementation.

Hm. Isn't the usual solution creating a temporary file in the same
directory, and then atomically moving it with os.rename()? At least
that's the Unix way that I am used to. The only other platform is
Windows and I'm sure there's a similar solution using native syscalls,
though I don't know what it is (and don't bring up the "Posix"
extension :-).

> I'm about +.5. I would expect this to be more portable than the application
> doing locking, but you have to provide something like that for those
> platforms anyway.

It seems that open(fn, 'c') is only part of the solution -- you'd
still have to do a move dance.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list