Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cdc0879

Browse files
committed
issue27186 -- initial docs, tests, and python version of os.fspath
1 parent 1f56e5f commit cdc0879

3 files changed

Lines changed: 51 additions & 0 deletions

File tree

Doc/library/os.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,15 @@ process and user.
186186
.. versionadded:: 3.2
187187

188188

189+
.. function:: fspath(path)
190+
191+
Return the string representation of the path.
192+
193+
If :class:`str` or :class:`bytes` is passed in, it is returned unchanged;
194+
otherwise, the result of calling ``type(path).__fspath__`` is returned, or an
195+
exception is raised.
196+
197+
189198
.. function:: getenv(key, default=None)
190199

191200
Return the value of the environment variable *key* if it exists, or

Lib/os.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1097,3 +1097,24 @@ def fdopen(fd, *args, **kwargs):
10971097
raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
10981098
import io
10991099
return io.open(fd, *args, **kwargs)
1100+
1101+
# Supply os.fspath()
1102+
def fspath(path):
1103+
"""Return the string representation of the path.
1104+
1105+
If str or bytes is passed in, it is returned unchanged.
1106+
"""
1107+
if isinstance(path, (str, bytes)):
1108+
return path
1109+
1110+
# Work from the object's type to match method resolution of other magic
1111+
# methods.
1112+
path_type = type(path)
1113+
try:
1114+
return path_type.__fspath__(path)
1115+
except AttributeError:
1116+
if hasattr(path_type, '__fspath__'):
1117+
raise
1118+
1119+
raise TypeError("expected str, bytes or os.PathLike object, not "
1120+
+ path_type.__name__)

Lib/test/test_os.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3095,5 +3095,26 @@ def test_resource_warning(self):
30953095
del iterator
30963096

30973097

3098+
class TestPEP519(unittest.TestCase):
3099+
"os.fspath()"
3100+
3101+
def test_return_bytes(self):
3102+
for b in b'hello', b'goodbye', b'some/path/and/file':
3103+
self.assertEqual(b, os.fspath(b))
3104+
3105+
def test_return_string(self):
3106+
for s in 'hello', 'goodbye', 'some/path/and/file':
3107+
self.assertEqual(s, os.fspath(s))
3108+
3109+
def test_garbage_in_exception_out(self):
3110+
vapor = type('blah', (), {})
3111+
for o in int, type, os, vapor():
3112+
self.assertRaises(TypeError, os.fspath, o)
3113+
3114+
def test_argument_required(self):
3115+
with self.assertRaises(TypeError):
3116+
os.fspath()
3117+
3118+
30983119
if __name__ == "__main__":
30993120
unittest.main()

0 commit comments

Comments
 (0)