[issue16125] open accepts arbitrary mode strings as long as they contain U

Robert Xiao report at bugs.python.org
Thu Oct 4 08:11:32 CEST 2012


New submission from Robert Xiao:

This issue affects Python 2.5 through 2.7, but not Python 3.

open accepts basically anything for the second argument, so long as it either starts with r, w, or a, or contains U somewhere in the string. Therefore, the following are all legal in Python 2.7.3:

>>> open('/tmp/a', 'wail')
<open file '/tmp/a', mode 'wail' at 0x100468ed0>
>>> open('/tmp/a', 'PAIL')
<open file '/tmp/a', mode 'PAIL' at 0x100468270>
>>> open('/tmp/a', 'rabid')
<open file '/tmp/a', mode 'rabid' at 0x100468ed0>
>>> open('/tmp/a', 'alpha[]')
<open file '/tmp/a', mode 'alpha[]' at 0x100468270>
>>> open('/tmp/a', 'raw')
<open file '/tmp/a', mode 'raw' at 0x100468270>

Because the mode string is literally a copy of the passed-in mode, it is not clear at all what the mode of the file actually is. For example, in the last case, I cannot write to the file even though the mode contains 'w', because the mode is actually 'r'. 

I think there are two ways to fix this: either fix the whole mode parsing logic in Objects/fileobject.c to resemble that in Modules/_io/fileio.c from Python 3 (which does proper validation), or just build and store the calculated mode (e.g. "rb") so it's at least possible to determine the file mode.

----------
components: IO
messages: 171922
nosy: nneonneo
priority: normal
severity: normal
status: open
title: open accepts arbitrary mode strings as long as they contain U
versions: Python 2.6, Python 2.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16125>
_______________________________________


More information about the Python-bugs-list mailing list