Python 导入优先级:包还是模块? [英] Python import precedence: packages or modules?

查看:30
本文介绍了Python 导入优先级:包还是模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不清楚如何正确命名这个问题.

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.pybar/__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 named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names."

这有点误导,因为解释器还会寻找一个名为 spam 的包(一个名为 spam 的目录,其中包含一个 __init__.py文件).由于目录条目在搜索之前被排序,如果包在同一目录中,包优先于同名模块,因为 spamspam.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆