Problematic behavior of the import statement when several module files have the same name.

Steven Bethard steven.bethard at gmail.com
Wed Mar 9 15:19:16 EST 2005


Xif wrote:
> Hello Everyone!
> 
> Here's a problem with relative imports:
> 
> Suppose I have a package called some_package (in a separate directory
> included in the PYTHONPATH, with an __init__.py file etc.)
> 
> This package has a module inside the directory, called "database", and
> therefore  residing in the file some_package/database.py.
> 
> Now, what if there's another module, for example inside the
> site-packages directory, with the same file name (i.e. database.py)?
> 
> We have a problem. Since although these modules have different absolute
> names ("some_package.database" for the first module, and just
> "database" for the second), when I try to do
> 
> import database
> 
> from inside some_package, it first of all tries to find the matching
> file in the some_package directory (i.e. do a relative import). Since
> it first checks the some_package directory, and finds database.py
> there,
> 
> import database
> 
> in fact imports the module with the absolute name
> some_package.database.

You've just re-discovered the reason you should always use absolute 
imports.  Check out:

http://www.python.org/doc/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module

STeVe



More information about the Python-list mailing list