issue27186: add open/io.open; patch by Jelle Zijlstra
diff --git a/Lib/_pyio.py b/Lib/_pyio.py
index 7b89347..40df79d 100644
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -161,6 +161,8 @@
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
+ if not isinstance(file, int):
+ file = os.fspath(file)
if not isinstance(file, (str, bytes, int)):
raise TypeError("invalid file: %r" % file)
if not isinstance(mode, str):
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index 53e776d..5584d6b 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -844,6 +844,32 @@
self.assertEqual(getattr(stream, method)(buffer), 5)
self.assertEqual(bytes(buffer), b"12345")
+ def test_fspath_support(self):
+ class PathLike:
+ def __init__(self, path):
+ self.path = path
+
+ def __fspath__(self):
+ return self.path
+
+ def check_path_succeeds(path):
+ with self.open(path, "w") as f:
+ f.write("egg\n")
+
+ with self.open(path, "r") as f:
+ self.assertEqual(f.read(), "egg\n")
+
+ check_path_succeeds(PathLike(support.TESTFN))
+ check_path_succeeds(PathLike(support.TESTFN.encode('utf-8')))
+
+ bad_path = PathLike(TypeError)
+ with self.assertRaisesRegex(TypeError, 'invalid file'):
+ self.open(bad_path, 'w')
+
+ # ensure that refcounting is correct with some error conditions
+ with self.assertRaisesRegex(ValueError, 'read/write/append mode'):
+ self.open(PathLike(support.TESTFN), 'rwxa')
+
class CIOTest(IOTest):