Skip to content

Instantly share code, notes, and snippets.

@k7hoven
Last active March 30, 2016 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k7hoven/defb7f2eb9ccd9dbd0be0063a475058e to your computer and use it in GitHub Desktop.
Save k7hoven/defb7f2eb9ccd9dbd0be0063a475058e to your computer and use it in GitHub Desktop.
Ridiculous, broken, hacky and flawed implementation of StringPath, instances of which are both instances of pathlib.Path and of str
>>> p = StringPath("foo/bar/baz")
>>> p
StringPath(PosixPath('foo/bar/baz'))
>>> isinstance(p, pathlib.Path)
True
>>> isinstance(p, str)
True
>>> str(p)
'foo/bar/baz'
>>> p + 'hello'
'foo/bar/bazhello'
>>> p / 'hello'
PosixPath('foo/bar/baz/hello')
>>> 'hello' / p
PosixPath('hello/foo/bar/baz')
>>> p.split('r')
['foo/ba', '/baz']
>>> pathlib.Path(p)
PosixPath('foo/bar/baz')
# A ridiculous, broken, hacky and flawed implementation of StringPath,
# instances of which are both instances of pathlib.Path and of str
#
# ONLY FOR EXPERIMENTATION AND DEMONSTRATION PURPOSES
#
# Because pathlib.Path has __slots__ defined, it is not possible to
# directly subclass both Path and str. Hence, the terrible hack.
# "Tested" in Python 3.5
import pathlib
class StringPath(str):
__class__ = pathlib.Path
def __init__(self, path):
if isinstance(path, str):
path = pathlib.Path(path)
self._path = path
self.__dict__.update(
{ n : getattr(path, n)
for n in dir(path)
if not n.startswith('_')}
)
self._parts = path.parts
def __repr__(self):
return "StringPath({})".format(repr(self._path))
def __truediv__(self, other):
return self._path / other
def __rtruediv__(self, other):
return other / self._path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment