Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.join with str subclass

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)?

like image 999
JBernardo Avatar asked Nov 13 '22 16:11

JBernardo


1 Answers

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.

like image 115
Matt Williamson Avatar answered Jan 09 '23 04:01

Matt Williamson