Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...