Re: Q on module names.

Guido.van.Rossum@cwi.nl
Fri, 26 Aug 1994 15:23:27 +0200

[This was emailed to me privately but the answer is a bit of trivia
that others might be interested in too...]

Mark Hammond writes:

> When I import a module, Python seems to store the name of the module with
> the pythonpath entry - eg, ".\module.py" is not uncommon.
> My error tracking code looks at this name to open the file, and jump to the
> error line. However, if I change directories, the relative file name is no
> longer valid. This obviously causes no problems for Python - only for me :)
> Is the absolute name available to me?

When Python parses and "compiles" a python module into a code object,
the pathname by which the module was found is inserted in the code
object. If the pathname was relative, a relative pathname will be
used. The code object is also copied to the .pyc file for the module,
so if a later run finds the same module along a different path, the
original pathname is still seen.

Translating relative pathnames into absolute pathnames is a tricky and
very non-portable business which I'd rather avoid -- especially on
UNIX sites that use automount facilities, since there the absolute
pathname will not have a permanent meaning.

A better solution is to avoid having relative pathnames in sys.path.
The moment this matters most is when the .pyc file is created, e.g. by
doing "import importall" after the library is installed. (BTW an
improved version of that hack will be in 1.1.)

The reason that it seems to cause no problems for Python is that if
Python can't find the file by opening the pathname from the code
object, it searches sys.path for a file with the same last component.
(This can still fail, but the likelihood is much less...)

> PS. would you prefer to see these sorts of questions posted to the
> newsgroup? (even though you will probably still give the answer - it may be
> useful to others, but its slightly more of a pain for me to post)

Yes, please post -- you can mail to python-list@cwi.nl and our
mailing list <-> newsgroup gateway software will post it.

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>