Created
April 14, 2016 06:29
-
-
Save mmysinger/0b5ae2cfb866f7013c387a2683c7fc39 to your computer and use it in GitHub Desktop.
Interoperability of fspath str only version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is posixpath from Python 3.4 based (not ideal, but it is what I had handy) | |
from os.path import _get_sep | |
# str-only. | |
def fspath(path): | |
try: | |
path = path.__fspath__() | |
except AttributeError: | |
pass | |
if isinstance(path, str): | |
return path | |
else: | |
raise TypeError | |
# os.path.join is meaty enough to test things | |
def join(a, *p): | |
"""Join two or more pathname components, inserting '/' as needed. | |
If any component is an absolute path, all previous path components | |
will be discarded. An empty last part will result in a path that | |
ends with a separator.""" | |
if not isinstance(a, bytes): | |
a = fspath(a) | |
sep = _get_sep(a) | |
path = a | |
try: | |
for b in p: | |
if not isinstance(b, bytes): | |
b = fspath(b) | |
if b.startswith(sep): | |
path = b | |
elif not path or path.endswith(sep): | |
path += b | |
else: | |
path += sep + b | |
except TypeError: | |
if all(isinstance(s, (str, bytes)) or hasattr(s, "__fspath__") for s | |
in (a,) + p): | |
# Must have a mixture of text and binary data | |
raise TypeError("Can't mix strings and bytes in path " + | |
"components") from None | |
raise | |
return path | |
# Simple "rich path" object that just passes through its constructor (bytes or str) | |
class RichPath: | |
def __init__(self, path): | |
self.path = path | |
def __fspath__(self): | |
return self.path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment