Does os.path relpath produce an incorrect relative path?

BlindAnagram BlindAnagram at nowhere.org
Thu May 25 03:49:06 EDT 2023


I am wondering whether I have misunderstood the semantics of os.path 
relpath or whether it has a bug.

Here is a short test program:

-----------------------------------------------------------
from os.path import relpath, split

src_path = 'C:\\lib\\src\\'

vcx_path = 'C:\\build.vs22\\lib\\lib.vcxproj'
rel_path = relpath(src_path, vcx_path)
print(f"{vcx_path = }\n{src_path = }\n{rel_path = }\n")

vcx_path = 'C:\\build.vs22\\lib\\'
rel_path = relpath(src_path, vcx_path)
print(f"{vcx_path = }\n{src_path = }\n{rel_path = }\n")

vcx_path = 'C:\\build.vs22\\lib\\lib.vcxproj'
rel_path = relpath(src_path, split(vcx_path)[0])
print(f"{vcx_path = }\n{src_path = }\n{rel_path = }\n")
-----------------------------------------------------------

and its output with Python 3.11:

-----------------------------------------------------------
vcx_path = 'C:\\build.vs22\\lib\\lib.vcxproj'
src_path = 'C:\\lib\\src\\'
rel_path = '..\\..\\..\\lib\\src'

vcx_path = 'C:\\build.vs22\\lib\\'
src_path = 'C:\\lib\\src\\'
rel_path = '..\\..\\lib\\src'

vcx_path = 'C:\\build.vs22\\lib\\lib.vcxproj'
src_path = 'C:\\lib\\src\\'
rel_path = '..\\..\\lib\\src'
-----------------------------------------------------------

The first of these three results produces an incorrect relative path 
because relpath does not strip off any non-directory tails before 
comparing paths.

Is this a bug or my misunderstanding of relpath semantics?

Comments would be appreciated as I don't waste developer time if this is 
not a bug.

   regards

     Brian


More information about the Python-list mailing list