多次导入同一模块
几个小时后,我发现了我的应用程序中出现错误的原因。我的应用程序的源代码结构如下:
main/
__init__.py
folderA/
__init__.py
fileA.py
fileB.py
确实,还有大约 50 个文件。但这不是重点。在 main/__init__.py
中,我有以下代码: fromfolderA.fileA import *
in folderA/__init__.py
我有以下代码:
sys.path.append(pathToFolderA)
在 folderA/fileB.py
我有这样的代码:
from fileA import *
问题是 fileA 被导入两次。但是,我只想导入一次。
解决这个问题的明显方法(至少对我来说)是将某些路径从 path
更改为 folderA.path
但我觉得 Python 甚至不应该在第一个错误出现地方。还有哪些其他解决方法不需要每个文件知道其绝对位置?
So after a few hours, I discovered the cause of a bug in my application. My app's source is structured like:
main/
__init__.py
folderA/
__init__.py
fileA.py
fileB.py
Really, there are about 50 more files. But that's not the point. In main/__init__.py
, I have this code: from folderA.fileA import *
in folderA/__init__.py
I have this code:
sys.path.append(pathToFolderA)
in folderA/fileB.py
I have this code:
from fileA import *
The problem is that fileA gets imported twice. However, I only want to import it once.
The obvious way to fix this (to me atleast) is to change certain paths from path
to folderA.path
But I feel like Python should not even have this error in the first place. What other workarounds are there that don't require each file to know its absolute location?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要以这种方式修改 sys.path,因为它提供了两种访问模块的方式(名称),从而导致您的问题。
请改用绝对导入或明确相对导入。 (不明确的相对导入可以用作较旧 Python 版本的最后手段。)
folderA/fileB.py
当然,您应该使用特定名称来代替该星号。
Don't modify sys.path this way, as it provides two ways (names) to access your modules, leading to your problem.
Use absolute or unambiguous-relative imports instead. (The ambiguous-relative imports can be used as a last resort with older Python versions.)
folderA/fileB.py
Of course, you should be using specific names in place of that star.
修改
sys.path
不是您在真实程序中所做的事情。与永久设置 PYTHONPATH 或将模块放在 Python 可以找到的位置相比,它会损害模块化和可移植性。永远不要使用
import *
。它会污染您的命名空间并使您的代码变得不可预测。您不希望将folderA放在
sys.path
上。它是main
的子包,并且应始终如此对待。始终使用绝对导入到顶级包:import main.folderA
而不是importfolderA
或其他任何内容;它将使您的代码更容易跟踪、移动和安装。Modifying
sys.path
isn't something you do in a real program. It hurts modularity and portability with no gain over setting PYTHONPATH permanently or putting your module in a place Python can find it.Never ever ever ever use
import *
. It pollutes your namespace and makes your code unpredictable.You don't want folderA on
sys.path
. It is a subpackage ofmain
and should always be treated as such. Always use absolute imports going to top-level packages:import main.folderA
rather thanimport folderA
or anything else; it will make your code a lot easier to follow and move around and install.