Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Possibly implementations of os.fspath()
# str-only.
def fspath(path):
try:
path = path.__fspath__()
except AttributeError:
pass
if isinstance(path, str):
return path
else:
raise TypeError
# Default to str, bytes allowed only when an argument.
def fspath(path, *, allow_bytes=False):
if allow_bytes and isinstance(path, bytes):
return path
try:
path = path.__fspath__()
except AttributeError:
pass
if isinstance(path, str):
return path
else:
raise TypeError
# Default to str, bytes allowed from anywhere.
def fspath(path, *, allow_bytes=False):
try:
path = path.__fspath__()
except AttributeError:
pass
if isinstance(path, str):
return path
elif allow_bytes and isinstance(path, bytes):
return path
else:
raise TypeError
# str or bytes allowed.
def fspath(path):
try:
path = path.__fspath__()
except AttributeError:
pass
if isinstance(path, (str, bytes)):
return path
else:
raise TypeError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment