[New-bugs-announce] [issue32965] Passing a bool to io.open() should raise a TypeError, not read from stdin
Erik Johnson
report at bugs.python.org
Tue Feb 27 16:25:48 EST 2018
New submission from Erik Johnson <palehose at gmail.com>:
When you open a filehandle using either True or False as the file, the open succeeds.
This has been reproduced using op/io.open on Python 3.6.4, 3.5.2, and 3.4.5, as well as with io.open() on Python 2.7.14.
This can be easily demonstrated in the REPL:
>>> f = open(False)
>>> f.read(10)
Lorem ipsum dolor sit amet
'Lorem ipsu'
>>> f.read(10)
'm dolor si'
>>> f.read(10)
't amet\n'
>>> f.read(10)
''
>>> f.close()
>>>
%
After the first read, I pasted in enough to stdin to exceed 10 bytes, and hit Enter. After the 2nd and third reads I had to hit Ctrl-d to exit back to the REPL. And, as a fun bonus, closing the filehandle quits the REPL.
This doesn't look like intended behavior. It doesn't make logical sense (why not just use sys.stdin if you want to read from stdin?), and isn't documented. This should either raise a TypeError, or the behavior should be documented. From the docs:
file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
Moreover, when you pass other values that don't match the above description, a TypeError is raised:
>>> open(123.456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: integer argument expected, got float
>>> open(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected str, bytes or os.PathLike object, not NoneType
>>> open(['wtf', 'am', 'i', 'doing???'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected str, bytes or os.PathLike object, not list
So, one of str, bytes, and os.PathLike are expected, right? And yet...
>>> isinstance(True, (str, bytes, os.PathLike))
False
>>> isinstance(False, (str, bytes, os.PathLike))
False
It should also be noted that when using the open() builtin on Python 2 instead of io.open(), you get a more logical result:
>>> open(False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, bool found
----------
messages: 313025
nosy: terminalmage
priority: normal
severity: normal
status: open
title: Passing a bool to io.open() should raise a TypeError, not read from stdin
type: behavior
versions: Python 2.7, Python 3.4, Python 3.5, Python 3.6
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32965>
_______________________________________
More information about the New-bugs-announce
mailing list