[Python-Dev] sys.path[0]

Thomas Heller theller@python.net
08 Jan 2003 10:03:15 +0100


Guido van Rossum <guido@python.org> writes:

> > [Kevin Altis brought this to my attention, so I'm cc-ing him]
> > 
> > The python docs state on sys.path:
> > 
> >   As initialized upon program startup, the first item of this list,
> >   path[0], is the directory containing the script that was used to
> >   invoke the Python interpreter. If the script directory is not
> >   available (e.g. if the interpreter is invoked interactively or if
> >   the script is read from standard input), path[0] is the empty
> >   string, which directs Python to search modules in the current
> >   directory first.
> > 
> > This is at least misleading.
> > 
> > It appears that for certain ways Python is started, the first item
> > on sys.path is a relative path name, or even empty, even if a script
> > was specified, and the path would have been available.
> 
> What's wrong with a relative pathname?  If you invoke the script using
> a relative pathname, why shouldn't that be what you get?  The docs
> don't say that it's the absolute pathname, so I don't think you can
> claim that the docs are misleading here.

Actually I don't care whether sys.path[0] contains an absolute or relative
pathname, but modules imported via a relative path entry get a mod.__file__
attribute which is also a relative pathname.

Changing the working directory then leads to strange results because
mod.__file__ is no longer a valid pathname: think of reload(), tracebacks,
and maybe more.

So maybe the __file__ attribute should be converted to an absolute path
during the module import?

> > Shouldn't Python convert sys.path to absolute path names, to avoid
> > these problems?
> 
> site.py converts sys.path entries to absolute pathnames, *except* for
> the path entry for to the script directory, because that is added to
> sys.path *after* site.py is run.
> 

Hehe. Does this prove that it's an implementation glitch?

> I'm disinclined to do anything about this, except perhaps warn that
> the script directory may be given as a relative path.

Well, doing "sys.path[0] = os.path.abspath(sys.path[0])" or
"sys.path = [os.path.abspath(p) for p in sys.path]" early enough
seems to fix it, although I would argue that should be Python's job.

Thomas