我这样构建我的 python 项目:
- project/
+- package/
+- db/
+- __init__.py
+- mydb.py
+- tests/
+- context.py
+- mytest.py
+- file.py
在 project/package/db/__init__.py 中,我将 mydb 声明为:
from package.db import mydb
通过这个声明,我可以在 file.py 中使用 mydb 函数,使用:
import package.db as db
db.mydb.myfunction()
但是我也想在 project/tests 目录中使用这个函数。所以,我添加了一个 project/tests/context.py 文件:
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import package.db as db
在 mytest.py 中:
from context import db
db.mydb.myfunction()
它运行良好。
但是 PyChar 说:
import package.db as db(在 context.py 中)是未使用的 import 语句from context import db(在 mytest.py 中)包含未解析的(上下文)引用
有没有办法改进这个项目结构以消除那些警告和错误?
谢谢
请您参考如下方法:
您的
package和tests文件夹中没有__init__.py文件;这意味着它不是 python 包。 - 如果你希望他们成为。您没有正确使用 import 语句;此外,您没有在
context.py文件中使用导入,因此为了修复它,您需要删除该行。我建议阅读 more here关于包裹;这将使您更深入地了解应该在
__init__.py文件中放入什么。
The
__init__.pyfiles are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the__all__variable, described later.
我将使用的结构:
- package_name
- db
- __init__.py
- my_db.py
- tests
- __init__.py
- my_test.py
- __init__.py
您唯一需要添加的代码在 my_db.py 文件中:
def my_function():
return 1
在您的 my_test.py 文件中,您将拥有:
from package.db import mydb
mydb.my_function()
这就是您所需要的;关于通过 __init__.py 文件更改导入,如果确实需要,请查看 __all__。
