简体   繁体   English

如何使用 python package 中的点进行相对导入?

[英]How to make relative import work with dot inside a python package?

I have a folder named as "model_dir" contains multiple *.py files.我有一个名为“model_dir”的文件夹,其中包含多个 *.py 文件。

model_dir:模型目录:

"model.py" “模型.py”

"utils.py" “utils.py”

inside model.py I can import like this: from utils import test在 model.py 中我可以这样导入: from utils import test

I want to copy the whole folder inside a package. Currently to make the import works inside the package I have two options:我想将整个文件夹复制到 package 中。目前要在 package 中进行导入,我有两个选择:

1- adding folder path to sys.path 1- 将文件夹路径添加到 sys.path

2- add dot for imports, like this: from.utils import test 2- 为导入添加点,如下所示: from.utils import test

Is there any way to make imports work without changing the code or sys path?有什么方法可以在不更改代码或系统路径的情况下使导入工作?

Have you tried including a blank __init__.py file in the model_dir folder?您是否尝试过在 model_dir 文件夹中包含一个空白的 __init__.py 文件? That should let python files import sibling files- I'm a novice dev myself and often run into pitfalls with imports inside packages, and I've found this link to be pretty helpful figuring out what I've done wrong这应该让 python 个文件导入同级文件——我自己是开发新手,经常在包内导入时遇到陷阱,我发现这个链接非常有助于找出我做错了什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM