Does anybody knows why the os.path.join function doesn't work with subclasses of str?
(I'm using Python3.2 x64 and Python2.7 x86 on Windows and the result is the same)
That's the code I have
class Path(str):
def __add__(self, other):
return Path(os.path.join(self, other))
p = Path(r'C:\the\path')
d = p + 'some_file.txt'
and the result I want:
'C:\\the\\path\\some_file.txt'
but the output is \\some_file.txt no matter the value of self.
I know I can do either str(self) or store it as self.path and use later, but why does os.join.path doesn't accept a str subclass nor raise an error (like when you use a number or any non string type)?
It looks like os.path.join uses the build in __add__ method, this can be verified by putting a print statement in the __add__ method.
>>> class Path(str):
... def __add__(self, other):
... print 'add'
... return Path(os.path.join(str(self), other))
...
>>> p = Path(r'/the/path')
>>> p + 'thefile.txt'
add
>>> class Path(str):
... def __add__(self, other):
... print 'add'
... return Path(os.path.join(self, other))
...
>>> p = Path(r'/the/path')
>>> p + 'file.txt'
add
add
# add printed twice
Simplest solution: Change
return Path(os.path.join(self, other))
to
return Path(os.path.join(str(self), other))
It works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With