This commit is contained in:
Brett Cannon 2016-06-15 12:56:31 -07:00
parent 1c5c8d8057
commit b38a469759
1 changed files with 21 additions and 4 deletions

View File

@ -149,7 +149,10 @@ The ``fspath()`` function will be added with the following semantics::
def fspath(path: t.Union[PathLike, str, bytes]) -> t.Union[str, bytes]: def fspath(path: t.Union[PathLike, str, bytes]) -> t.Union[str, bytes]:
"""Return the string representation of the path. """Return the string representation of the path.
If str or bytes is passed in, it is returned unchanged. If str or bytes is passed in, it is returned unchanged. If __fspath__()
returns something other than str or bytes then TypeError is raised. If
this function is given something that is not str, bytes, or os.PathLike
then TypeError is raised.
""" """
if isinstance(path, (str, bytes)): if isinstance(path, (str, bytes)):
return path return path
@ -158,10 +161,16 @@ The ``fspath()`` function will be added with the following semantics::
# methods. # methods.
path_type = type(path) path_type = type(path)
try: try:
return path_type.__fspath__(path) path = path_type.__fspath__(path)
except AttributeError: except AttributeError:
if hasattr(path_type, '__fspath__'): if hasattr(path_type, '__fspath__'):
raise raise
else:
if isinstance(path, (str, bytes)):
return path
else:
raise TypeError("expected __fspath__() to return str or bytes, "
"not " + type(path).__name__)
raise TypeError("expected str, bytes or os.PathLike object, not " raise TypeError("expected str, bytes or os.PathLike object, not "
+ path_type.__name__) + path_type.__name__)
@ -294,6 +303,14 @@ The C API will gain an equivalent function to ``os.fspath()``::
path_repr = PyObject_CallFunctionObjArgs(func, NULL); path_repr = PyObject_CallFunctionObjArgs(func, NULL);
Py_DECREF(func); Py_DECREF(func);
if (!PyUnicode_Check(path_repr) && !PyBytes_Check(path_repr)) {
Py_DECREF(path_repr);
return PyErr_Format(PyExc_TypeError,
"expected __fspath__() to return str or bytes, "
"not %S",
path_repr->ob_type);
}
return path_repr; return path_repr;
} }