问题
Suppose I have a module foo.py
and a package foo/
. If I call
import foo
which one will be loaded? How can I specify I wand to load the module, or the package?
回答1:
I believe the package will always get loaded. You can't work around this, as far as I know. So change either the package or the module name. Docs: http://docs.python.org/tutorial/modules.html#the-module-search-path
回答2:
Actually, it is possible (this code is not well tested, but seems to work).
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')
Running
$ python test1.py
foo package loaded
$ python test2.py
foo module loaded
回答3:
Maybe you want to move your classes from foo.py
module to __init__.py
.
This way you'll be able to import them from the package as well as importing optional subpackages:
File foo/__init__.py
:
class Bar(object):
...
File mymodule.py
:
from foo import Bar
from foo.subfoo import ...
Nonetheless I would like somebody to double-check this approach and let me know if it's correct or the __init__
module shouldn't be used like that.
来源:https://stackoverflow.com/questions/6393861/how-python-deals-with-module-and-package-having-the-same-name