importing modules: bug or not ?

Stefan Seefeld seefeld at sympatico.ca
Fri Jun 15 13:22:46 EDT 2001


hi there,

I'v come across a (pretty particular) situation that
appears to reveal a bug in python's import mechanism.
Please correct me if I'm wrong...

Please consider this tiny script (let's call it bug.py):

#!/usr/local/bin/python

import sys
import os
import Synopsis

__old_dir = os.getcwd()
os.chdir('html')

import Synopsis.Formatter
os.chdir(__old_dir)

-----------------------------

it results in 

ImportError: No module named Formatter

even though Formatter is a valid module inside Synopsis.

This happens only in this particular context:

imagine my PYTHONPATH variable to be 'home/stefan/synopsis'.
'synopsis' contains (among others) the 'Synopsis' module
which I want to use for the imports in the script, as well
as the script itself.

This means that when running the script, the sys.path variable
will contain the directory part of argv[0] (i.e. '..' if I called
the script like '../bug.py'), as well as home/stefan/synopsis.

This is important since when I copy the script to a different place,
The path that is used for the import is the second entry in
sys.path, and everything works fine. Only if the script is
in the same directory as the Synopsis module I get the error.

Second, the problem goes away if I don't import 'Synopsis' on top
of the script. This sounds like a caching problem, i.e. some
internal representation of module/module-paths getting invalidated
through the use of chdir.

Any clarification would be highly appreciated, as I need to find
a workaround for this.

Thanks,
		Stefan



More information about the Python-list mailing list