[Python-Dev] A wart which should have been repaired in 3.0?

Paul Moore p.f.moore at gmail.com
Tue Dec 30 10:36:26 CET 2008

2008/12/30 Phillip J. Eby <pje at telecommunity.com>:
> You know, all this path separator and list complication isn't really
> necessary, when you can just take the os.path.dirname() of the return from
> commonprefix().
> Perhaps we could just add that recommendation to the docs?

Actually, consider the following (on Windows):

Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.commonprefix(["foo\\bar\\baz", "foo/bar/boink"])

This very clearly shows that commonprefix is a string operation rather
than a path operation, as it does not respect the equivalence of
os.sep and os.altsep. In path semantics, the common prefix is
"foo/bar" (or equivalently "foo\\bar").

I'm not sure how to deal with this, except by recommending that all
paths passed to os.path.commonprefix should at the very least be
normalised via os.path.normpath first - which starts to get clumsy
fast. So the "recommended" usage to get the common directory is

    paths = [...]
    common = os.path.dirname(os.path.commonprefix([os.path.normpath(p)
for p in paths]))



More information about the Python-Dev mailing list