schui schui - 1 year ago 65
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 Source

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 and a package foo/.


print("foo module loaded")

File foo/

print("foo package loaded")


import foo


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 
foo package loaded

$ python 
foo module loaded
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download