[英]How to import using a top level path in Python?
I'm developing a python framework and want to do imports based on the top-level package (the project name). 我正在开发python框架,并希望基于顶级包(项目名称)进行导入。 Users will use the framework by copying the entire framework and writing their own modules within. 用户将通过复制整个框架并在其中编写自己的模块来使用该框架。
My current structure looks like this: 我当前的结构如下所示:
myapp/
config.py
docs/
framework/
main.py
utils.py
file.py
lib/
some_module.py
unit_tests/
test_utils.py
I want to be able to use the following import in python files in lib and unit_tests in the following way: 我希望能够通过以下方式在lib和unit_tests中的python文件中使用以下导入:
from myapp.framework import utils
Is there a simple way to do this? 有没有简单的方法可以做到这一点? I've tried doing sys.path.append() hacks but they don't really work. 我曾尝试过进行sys.path.append()黑客攻击,但实际上并没有用。 If there is a truly pythonic way to achieve this, I don't mind going extra lengths to get it working. 如果有一种真正的Python方式可以实现这一目标,那么我不介意花费额外的精力来使其工作。
EDIT: Well I tried the sys.path.append() again and it actually works but it really is an in-elegant solution and I'd really like to hear if there's another way. 编辑:好吧,我再次尝试了sys.path.append(),它确实起作用了,但这确实是一个优雅的解决方案,我真的很想听听是否还有其他方法。
For short: You can't have two modules with the same name one inside the other. 简而言之:您不能在两个模块之间使用相同的名称。 You have the myapp
folder and the myapp.py
file 您有myapp
文件夹和myapp.py
文件
That's because of the order of importing modules. 那是因为导入模块的顺序。
So, if you're trying to import myapp.lib.some_module
in config.py the interpreter will first see that you have myapp.py in the same folder and literaly try to import lib.some_module
from that file, which doesn't exist. 因此,如果您尝试在config.py中import myapp.lib.some_module
,那么解释器将首先看到您在同一文件夹中有myapp.py并从字面上尝试从该文件导入lib.some_module
,该文件不存在。
Would be something as trying to import myapp.myapp.lib.some_module
from outside that module. 就像尝试从该模块外部导入myapp.myapp.lib.some_module
。
So, the best thing for you to do is to rename the myapp.py
file 因此,最好的方法是重命名myapp.py
文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.