[Python-Dev] os.path.dirname misleading?

Kevin Altis altis@semi-retired.com
Wed, 12 Mar 2003 08:43:04 -0800


I'm not sure whether to classify this as a bug or a feature request.
Recently, I got burned by the fact that despite the name, dirname() does not
return the expected directory portion of a path if you pass it a directory,
instead it will return the parent directory because it uses split.

That it uses split is clearly documented and also evident in the source,
though both fail to point out the case of passing in a directory path.

"dirname(path)
Return the directory name of pathname path. This is the first half of the
pair returned by split(path)."

# Return the head (dirname) part of a path.

def dirname(p):
    """Returns the directory component of a pathname"""
    return split(p)[0]

However, to get what I would consider correct behavior based on the function
name, the code would need to be:

def dirname(p):
    """Returns the directory component of a pathname"""
    if isdir(p):
        return p
    else:
        return split(p)[0]

Changing dirname() may in fact break existing code if people expect it to
just use split, so a dirname2() function seems called for, but that seems
silly, given that dirname should probably be doing an isdir() check.

ka