schui schui - 2 days ago 5
Python Question

Why is there a import error when packagename equal filename?

I'm wondering why python has a problem when the packagename of the import statement is equal to the actual filename of the python script. Can you explain it deeply? It's always a stupid mistake. Thank you!

Answer

If i have understood your question correctly, you are asking how to handle package and module import if they have the same name. Suppose you have a module foo.py and a package foo/.

File foo.py:

print("foo module loaded")

File foo/__init__.py:

print("foo package loaded")

File test1.py:

import foo

File test2.py:

import os, imp

def import_module(dir, name):
    """ load a module (not a package) with a given name 
        from the specified directory 
    """
    for description in imp.get_suffixes():
        (suffix, mode, type) = description
        if not suffix.startswith('.py'): continue
        abs_path = os.path.join(dir, name + suffix)
        if not os.path.exists(abs_path): continue
        fh = open(abs_path)
        return imp.load_module(name, fh, abs_path, (description))

import_module('.', 'foo')

Now running the tests:

$ python test1.py 
foo package loaded

$ python test2.py 
foo module loaded
Comments