[英]How do i structure my Python submodule with a lot of files, so that i have to import only one module
I have a Python Project named osinttool
which contains a folder named osinttool
which contains the .py-files.我有一个名为
osinttool
的 Python 项目,其中包含一个名为osinttool
的文件夹,其中包含 .py 文件。 In this folder, I have a folder named database that contains a file named db.py and there are several functions for creating entries in my database, deleting them and so on.在这个文件夹中,我有一个名为 database 的文件夹,其中包含一个名为 db.py 的文件,并且有几个函数可以在我的数据库中创建条目,删除它们等等。 In my other files, I just import like that
'from database import db'
and that works fine.在我的其他文件中,我只是像
'from database import db'
那样'from database import db'
并且工作正常。
The problem is, there is such a lot of code in db.py and I want to split up the code so that every different resource has its own file, but I still want to only import one module to use all of these databases function.问题是,db.py 中有这么多代码,我想拆分代码,以便每个不同的资源都有自己的文件,但我仍然只想导入一个模块来使用所有这些数据库功能。 It would be super nice if I don't even have to change anything in the files that use the DB-module.
如果我什至不必更改使用 DB 模块的文件中的任何内容,那就太好了。
How could I do that?我怎么能那样做?
I recommend converting db
into a package in itself, with a directory structure like below, including an __init__.py
file which provides the package's public API.我建议将
db
本身转换为一个包,其目录结构如下所示,包括一个__init__.py
文件,它提供了包的公共 API。
- db
- __init__.py
- dbtools.py
Suppose you have a module dbtools.py
inside your db
package, which defines a function initialize_db_connection
.假设您的
db
包中有一个模块dbtools.py
,它定义了一个函数initialize_db_connection
。 You could then create an __init__.py
file at the same level with contents like:然后,您可以在同一级别创建一个
__init__.py
文件,其内容如下:
from .dbtools import initialize_db_connection
You could then import this as from db import initialize_db_connection
, even though the function is within a module in the package.然后您可以将其导入为
from db import initialize_db_connection
,即使该函数位于包中的模块内。
In the modules which already import as from database import db
, your function would be accessible as db.initialize_db_connection
.在已经作为
from database import db
导入的模块中,您的函数可以作为db.initialize_db_connection
访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.