Add to `open` the missing modes that PHP `fopen` has

In Python open (Python docs: open), we have the following modes available:

r - reading only, file must exist.
w - writing only, file will be created if it does not exist, file will be truncated if it does exist.
x - writing only, file must not exist, and will be created.
a - writing only, file will be created if it does not exist, all writes write at end of file.
r+ - reading and writing, file must exist.
w+ - reading and writing, file will be created if it does not exist, file will be truncated if it does exist.

PHP fopen (PHP docs: fopen) supports all of the above, as well as the following additional modes:

x+ - reading and writing, file must not exist, and will be created.
c - writing only, file will be created if it does not exist, file will not be truncated if it does exist.
c+ - reading and writing, file will be created if it does not exist, file will not be truncated if it does exist.

I believe these modes should be added to Python. I previously mentioned this in `open()`able objects - #16 by rrolls in the context of interfaces, and I went into much more detail on my rationale there.

I didn’t previously suggest actually adding it to the builtin open as that was off-topic there, but I was motivated to start this thread today upon running into a use case for c+ mode again.

I’m currently using the following workaround: (but not quite - see my follow-up post below)

import os
with os.fdopen(os.open('file', os.O_CREAT | os.O_RDWR), 'r+b') as f:
  ...

but I’d really like to be able to write this as simply

with open('file', 'c+b') as f:
  ...

which should do the equivalent to the above working snippet. c mode should be handled in the same way, but with O_RDONLY instead of O_RDWR. (On Windows, it looks like O_BINARY would also be needed if 'b' is in the mode string.)

As for x+ mode, I’ll quote myself from my earlier post:

x+ in Python does not raise an exception if I request it (using builtin open) but I’ve not tested thoroughly if it actually does what I expect it to do. If Python does already implement this mode, it ought to be documented; otherwise, it should (preferably, IMO) be implemented and documented, or if it’s decided that Python should not support this mode, attempting to use this mode should raise an exception and, again, this should be documented.

(PHP also has a+ mode. I consider this mode quite a footgun, as append mode forces all writes to the end of the file so it doesn’t really make sense (to me) to combine it with the ability to read. Therefore I haven’t listed this one above as I don’t believe it should be added. But if others have a strong desire for it to be added for some reason, I wouldn’t object. It’s also possible, like x+, that it’s already available in Python but not documented, in which case it can stay as it is but ought to be documented.)


Are there any particular objections to these modes being added? (and/or is anyone already working on this?)

If not, I can (at some point) do some more serious testing across Linux and Windows of the existing and newly proposed modes, figure out for sure whether x+ is already implemented, have a stab at implementing it in CPython along with some tests, and suggest some improved docs.

Snag: permissions mode of newly-created file

I wrote above that I’m not quite using the workaround above.

I had to add mode=0o644 to the os.open call. Without it, it creates the file with permissions 755 (due to the default mode being 0o777 and this being combined with the usual default umask by the OS).

However, I notice that if I create a file with the builtin open, e.g. with mode='w', it creates it with mode 644 as desired anyway. I realise Python must have chosen to do this, as relying on umask alone would surely result in 755 like for os.open. I also notice builtin open does not seem to have an argument to set the desired permissions mode. I’m sure I’ll learn more about this when I actually check the relevant [C]Python source, but for now my conclusions are:

  • The file permissions on a file created by builtin open should not depend on its mode argument.
  • Preferably, a new argument should be added to open to allow the caller to decide what file permissions should be set (subject to umask as usual). This is entirely separate from my proposal to add c, c+ and x+ modes, but I think it makes sense to add, and in that case, it makes sense to add at the same time.
    • There’s a bikeshedding opportunity: what to call that new argument? The existing mode argument of open is the string that is r, w, w+, etc. determining how to open the file. The existing mode argument of os.open is the integer determining what permissions mode should be set if the file is newly created (and ignored if not). To add a permissions mode argument to builtin open, it obviously can’t be called mode.

My current helper function

This is barely tested so far, but I think it’s worth posting for reference anyway for the c modes:

import os
import pathlib
import sys
import typing

def creat(path: pathlib.Path, mode: typing.Literal['c', 'cb', 'c+', 'c+b']):
    plus = '+' in mode
    binary = 'b' in mode
    os_mode = os.O_CREAT
    if plus:
        os_mode |= os.O_RDWR
    else:
        os_mode |= os.O_RDONLY
    if binary and sys.platform == 'win32':
        os_mode |= os.O_BINARY
    assert mode.startswith('c')
    r_mode = 'r' + mode[1:]
    return os.fdopen(os.open(path, os_mode, mode=0o644), r_mode)

One can then write with(creat(...)) as f like one can currently write with(open(...)) as f.

In practice this is only really useful for b modes, as it doesn’t offer all the other arguments (encoding, newline, etc.) that you’d want to be able to pass to os.fdopen. I haven’t bothered adding a **kwargs because that provides no helpful typing information, and I’m certainly not going to the effort (right now) to add all the individual arguments and overloads (as my use case only uses c+b). But it should at least illustrate what I’m trying to achieve, and perhaps serve as a starting point for anyone else with a similar need.

(I’ll update the above snippet if further testing reveals any issues with it that can be solved without making it huge.)

So are you aware of any use cases for the other modes (c, cb and ``c+, and the various x+modes)? Or is this simply a request to extend the functionality "for completeness"? Your workaround code seems pretty reasonable for a niche case, so even the case forc+b` isn’t that compelling IMO.

I don’t know what happened with the “openable objects” thread - it seems to have died down with no final plan for implementation. Maybe @barneygale can comment on that?

It seems that C and Python agree, and both don’t have those extra PHP modes.Are those two extra modes used much in PHP? Any algorithms made more elegant by their use?

Look at the opener parameter of open().

I just tried the first “missing” case, x+, and it seems to work for me:

with open('test', 'x+') as f:
    f.write('foo')
    f.seek(0)
    print(f.read())

That printed “foo”. Attempt This Online!

1 Like

Should this mimic PHP/C or should python go for a more descriptive function interface instead? The problem with modeis that I have to read the docs every time I encounter it.

Maybe consider:

open(
    path,
    reading=True,
    writing=True,
    if_exists="truncate",
    if_not_exists="create",
)
  • The parameter if_exists can be "truncate" (default), "append" or "error".
  • The parameter if_not_existscan be "create"(default) or "error".
  • The parameters above are only useful if writingis True.
  • Setting both options to "error"is useless, but should just give an error :grinning_face_with_smiling_eyes:.

Or maybe add these new keyword arguments to Path only and treat the old openinterface with its modeas legacy.

2 Likes

Having a bunch of kwargs does sound a lot more Pythonic, yes! While the string modes are well known to experienced programmers and seem like the obvious choice if you’re writing a new language, you’re right that they’re not entirely obvious to someone who’s not encountered them before or doesn’t use them much.

I’ll point out that with your kwargs you’re missing an important option: if_exists="no_truncate", i.e. open the file without truncating it (r, r+, c, c+ modes). Also "append" should not be a possible value for if_exists, rather it should be a separate bool kwarg append, due to its quirky behavior of forcing all writes to the end of the file (rather than just setting the cursor to end of file upon open).

I did have the thought that we would naturally want to separate it into a bunch of bool kwargs:

def open(
  path,
  reading=True,
  writing=False,
  truncate=None,
  must_exist=None,
  must_create=False,
  append=False,
  ... # binary, encoding, errors, etc.
)

but sadly the problem with this is that the default of truncate would be whatever the value of writing is, and the the default of must_exist would be the logical negation of the value of writing. Which you could do, by setting the default to None (as indicated) and putting that logic in, but then you have to explain that in the documentation, and I think you then lose some of the value of doing this.

With either method you’d also have to explicitly set reading to False if you only wanted writing, which also feels a little odd. It makes you want to combine them back into a single arg r, w or rw.

Furthermore, if we’re going to change the function signature so dramatically, I’d argue it should also be split into open_binary and open_text. There’s a ton of arguments that only apply to text mode, and dealing with the return value is annoying when it can depend on whether 'b' is in the mode string (have you seen the type stubs for open? They’re why I didn’t want to support all those arguments in my creat snippet). At that point, it does indeed start to sound sensible to soft deprecate built-in open and put the new interface in Path.


BUT. As compelling as these ideas are, they’re major changes that would require a PEP, replace a longstanding interface, and have their own issues that would need to be resolved.

So for now, I’d prefer to keep this thread about simply adding the c and c+ modes (and documenting x+, as Stefan has pointed out it apparently works), as a much more targeted improvement, that would add functionality matching a current pattern without replacing or deprecating anything.

(I’ve obviously not helped my case by talking about the permissions mode earlier. So for the sake of adding c and c+, obviously open can create files, so it has existing logic that determines what the permission mode is, and c and c+ can just apply that same logic. Adding a permissions mode argument to open is a potentially good idea, but would be a separate, unrelated improvement.)

(edited to fix Markdown and put an explicit list of new modes)

The point of c+ mode is to fill the gap left by r+ and w+. r+ will always fail if the file doesn’t exist and w+ will always lose data if the file exists (and isn’t empty). c+ gives you a single open call that will both create the file if it doesn’t exist and avoid losing data (by truncation) if it does.

My use case uses c+b because from experience I’ve determined I personally much prefer to work with file objects in binary and then separately encode/decode my strings. I think it’s easy to see that c+ mode would be useful for anyone who has the same need outlined above but prefers to work with text-based file objects where Python automatically deals with encoding and line endings.

Stefan has pointed out x+ already exists so I presume x+b also already exists, and I believe these only need to be properly documented, so in that case I don’t think I need to justify them.

That only leaves c and cb. You could argue that these modes “aren’t needed”, because c+ and c+b already let you do everything that c and cb would. It’s something I would likely never use myself. I can see a possible, though somewhat contrived use for cb: open a file, write a block of data to a particular location and then close it again, without ever reading it. But yes, mainly I think c and cb should exist “for completeness”, and in this case I do think it’s justified: it would be surprising if c+ existed and c didn’t; arguing that c mode shouldn’t exist because you could just use c+ is like arguing that w mode shouldn’t exist because you could just use w+.

My justification for c+b, when the workaround exists, is simply: one shouldn’t have to use a workaround.

  • with open('file') as f: is something you can write in Python from day one, heck, without even an import. Setting the mode to r+, w+ is another easy step. c+ in a way combines those two modes, and it’s weird that you can’t ask for that combination without doing totally different things involving fdopen. To a newbie it’s nonsense, and to an experienced programmer it’s a nuisance.
  • Although I can use the creat workaround I posted above, it’s far from ideal. It works for my case where I only need c+b and don’t need any extra arguments. It would not work nearly as well for anyone who wants to use text mode or otherwise needs the extra arguments (they would have to either put **kwargs and lack a lot of typing information, or put a lot of extra boilerplate). And I have to decide whether to write open or my_module.creat depending on mode, when I should just be able to write open in all cases.
  • Without c+, the natural thing to do is to try r+ first, realise it gives a FileNotFoundError if the file doesn’t exist, and then settle on try: open(p, 'r+'); except: open(p, 'w+'). It’s obvious and only uses the “nice, friendly” open function. This solution ends up appearing to work, well enough that you bung it in a function somewhere and never think about it again, but suffers from TOCTTOU and one day causes something nasty. If c+ was in Python’s built-in open, and documented, it would become the natural thing to do.
    • Long ago, I was a PHP programmer. This is where I first learnt of the idea of c+ mode: I read the PHP manual and saw it there. At first I didn’t know why it was useful, so it was a curiosity in the back of my mind. But having that curiosity is what led me to one day realise the TOCTTOU issue, and thus realise why c+ is useful. That curiosity is likely also why I didn’t feel satisfied with the try-except solution in Python, and why I felt I must look harder for a solution (and end up with this fdopen workaround).

In short: Yes, my workaround works, but I think having the c modes built in would be far superior, and it’s a very minor impact: it simply allows a few new possible options in a function argument.

2 Likes

First off, I understand and support Rob’s use case.

I think more broadly: finding instances of this kind of pattern being done in existing codebases (either in Python or inside PHP codebases) would make supporting this kind of change more justifiable.

For some added context, I did a tiny bit of research and found that C’s fopen() uses c in a completely different way than PHP:

       c (since glibc 2.3.3)
              Do not make the open operation, or subsequent read and
              write operations, thread cancelation points.  This flag is
              ignored for fdopen().

Compare to PHP’s c / c+ modes:

c - Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

c+ - Open the file for reading and writing; otherwise it has the same behavior as 'c'.

I can confirm it works. So, more important than what the OP: those should be documented.

1 Like

Python already supports the a+ mode. It seeks to the end of the file on opening, of course, but you can use seek on it.

You can seek, but every write to a file opened using a/a+ mode will append to the end of the file, instead of using the seek position.

2 Likes