bpo-30432: FileInput doesn't accept PathLike objects for file names (#1732)

* Allow FileInput to accept a single PathLike object as a parameter for `files`

Fixes

bpo-30432: FileInput doesn't accept PathLike objects for file names

* Address comments from @ambv
This commit is contained in:
Roy Williams 2017-05-22 22:24:17 -07:00 committed by Łukasz Langa
parent d618c8c6d3
commit 002665a9da
2 changed files with 17 additions and 0 deletions

View File

@ -189,6 +189,8 @@ class FileInput:
mode="r", openhook=None): mode="r", openhook=None):
if isinstance(files, str): if isinstance(files, str):
files = (files,) files = (files,)
elif isinstance(files, os.PathLike):
files = (os.fspath(files), )
else: else:
if files is None: if files is None:
files = sys.argv[1:] files = sys.argv[1:]

View File

@ -21,6 +21,7 @@ except ImportError:
from io import BytesIO, StringIO from io import BytesIO, StringIO
from fileinput import FileInput, hook_encoded from fileinput import FileInput, hook_encoded
from pathlib import Path
from test.support import verbose, TESTFN, check_warnings from test.support import verbose, TESTFN, check_warnings
from test.support import unlink as safe_unlink from test.support import unlink as safe_unlink
@ -530,6 +531,20 @@ class FileInputTests(unittest.TestCase):
self.assertRaises(StopIteration, next, fi) self.assertRaises(StopIteration, next, fi)
self.assertEqual(src.linesread, []) self.assertEqual(src.linesread, [])
def test_pathlib_file(self):
t1 = None
try:
t1 = Path(writeTmp(1, ["Pathlib file."]))
with FileInput(t1) as fi:
line = fi.readline()
self.assertEqual(line, 'Pathlib file.')
self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 1)
self.assertEqual(fi.filename(), os.fspath(t1))
finally:
remove_tempfiles(t1)
class MockFileInput: class MockFileInput:
"""A class that mocks out fileinput.FileInput for use during unit tests""" """A class that mocks out fileinput.FileInput for use during unit tests"""