How to do relpath implementation on 2.5

ryles rylesny at gmail.com
Sun Aug 9 09:49:42 CEST 2009


On Aug 8, 9:08 pm, Brian Allen Vanderburg II
<BrianVanderbu... at aim.com> wrote:
> I've coded my own 'relpath' implementation for 2.5 (shown below) and I
> want to make sure it follows as closely as it should to 2.6 and later.  
> I've got a question regarding that.  When attempting to convert to a
> relative path and it is not possible for some reason (different drive or
> UNC share), should that be an error or should it return the absolute
> path of the target?  I'm using Debian so I don't have 2.6 available
> right now for testing.

Usually Python source code is easily browsed at:

http://svn.python.org/view/

Unfortunately the server is down right now.

The implementation in 2.6 raises a ValueError exception. Here is the
function from ntpath.py:

def relpath(path, start=curdir):
    """Return a relative version of a path"""

    if not path:
        raise ValueError("no path specified")
    start_list = abspath(start).split(sep)
    path_list = abspath(path).split(sep)
    if start_list[0].lower() != path_list[0].lower():
        unc_path, rest = splitunc(path)
        unc_start, rest = splitunc(start)
        if bool(unc_path) ^ bool(unc_start):
            raise ValueError("Cannot mix UNC and non-UNC paths (%s and
%s)"
                                                                %
(path, start))
        else:
            raise ValueError("path is on drive %s, start on drive %s"
                                                % (path_list[0],
start_list[0]))
    # Work out how much of the filepath is shared by start and path.
    for i in range(min(len(start_list), len(path_list))):
        if start_list[i].lower() != path_list[i].lower():
            break
    else:
        i += 1

    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return curdir
    return join(*rel_list)



More information about the Python-list mailing list