Skip to content

Instantly share code, notes, and snippets.

@lmazuel
Last active September 19, 2018 14:57
Show Gist options
  • Save lmazuel/32ee3940821714c198c67538c0f765b4 to your computer and use it in GitHub Desktop.
Save lmazuel/32ee3940821714c198c67538c0f765b4 to your computer and use it in GitHub Desktop.
Fspath for Python < 3.6
def fspath(path):
'''https://www.python.org/dev/peps/pep-0519/#os'''
if isinstance(path, (str, bytes)):
return path
# Work from the object's type to match method resolution of other magic
# methods.
path_type = type(path)
try:
path = path_type.__fspath__(path)
except AttributeError:
# Added for Python 3.5 support.
if isinstance(path, pathlib.Path):
return str(path)
elif hasattr(path_type, '__fspath__'):
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, pathlib.Path or os.PathLike object, not "
+ path_type.__name__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment