Python导入优先级:包还是模块? [英] Python import precedence: packages or modules?
问题描述
我不清楚如何正确命名这个问题。
I wasn't clear how to correctly name this question.
案例1
假设我有以下目录结构。
Assume that I have the following directory structure.
foo
|
+- bar/__init__.py
|
+- bar.py
如果我有
from foo import bar
怎么做我知道正在导入哪个栏( bar.py
或 bar / __ init __。py
)?有没有简单的方法可以自动检测到这种情况?
How do I know which bar (bar.py
or bar/__init__.py
) is being imported? Is there any easy way to automatically detect this from occurring?
案例2
foo
|
+- foo.py
|
+- other.py
如果other.py有行
If other.py has the line
import foo
我怎么知道导入了哪个foo(foo或foo.foo)?再次,是否有任何简单的方法可以自动检测到这种情况?
How do I know which foo (foo or foo.foo) is being imported? Again, is tehre any easy way to automatically detect this from occurring?
推荐答案
TLDR;如果一个包位于同一目录中,则它优先于同名模块。
TLDR; a package takes precedence over a module of the same name if they are in the same directory.
来自文档:
导入名为
spam
的模块时,解释程序会搜索名为spam.py <的文件
在当前目录中,然后在环境变量PYTHONPATH
指定的目录列表中。这与shell变量PATH具有相同的语法,即,一个目录名列表。
"When a module named
spam
is imported, the interpreter searches for a file namedspam.py
in the current directory, and then in the list of directories specified by the environment variablePYTHONPATH
. This has the same syntax as the shell variable PATH, that is, a list of directory names."
这有点误导,因为解释器也会寻找一个名为<$ c $的包c>垃圾邮件(一个名为垃圾邮件
的目录,其中包含 __ init __。py
文件)。由于目录条目在搜索之前已经排序,因此如果它们位于同一目录中,则包优先于具有相同名称的模块,因为 spam
位于垃圾邮件之前。 py
。
This is a bit misleading because the interpreter will also look for a package called spam
(a directory called spam
containing an __init__.py
file). Since the directory entries are sorted before searching, packages take precedence over modules with the same name if they are in the same directory because spam
comes before spam.py
.
请注意,当前目录是相对于主脚本路径的( __ name__ == '__main__'为True
)。因此,如果你在 / home / billg
调用 /foo/bar.py
,当前目录指的是 / foo
。
Note that "current directory" is relative to the main script path (the one where __name__ == '__main__' is True
). So if you are at /home/billg
calling /foo/bar.py
, "current directory" refers to /foo
.
这篇关于Python导入优先级:包还是模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!