python - 在模块之间共享资源的良好做法?

标签 python module namespaces global

<分区>

我正在重组我的代码,因此创建了新的命名空间。我正在为模块更改“静态”类(每个方法中带有@staticmethod 的类)。这是要走的路,对吧?

问题是我对如何在这些模块之间共享资源有疑问。

假设我有一个模块,我从中进行与数据库的所有连接,当然所有类/方法都共享存储数据库游标的变量(我使用的是 SQLite)。现在,在不同的模块中,它们也必须共享光标。

Graphical representation of dependences

那么,我的想法:

  • 在每个模块中声明全局变量。但是全局人是邪恶的,他们吃 child 并偷走我们的工作。所以我不知道这是不是要走的路。

    '''Sub Module 1'''
    
    global database_cursor
    
  • 用原始的 database_cursor 导入“父亲”database_module 并使用如下内容:

    '''Sub Module 1'''
    
    db_cursor = database_module.database_cursor
    

在这种情况下,这秒看起来不错,但我认为在很多情况下会导致递归导入,我想这是应该避免的事情。

最佳答案

你的第二种方法是要走的路。 Python 导入本质上是单例的。当一个模块被多次导入时,它只会在第一次被执行。随后的导入从全局变量中获取模块对象实例。更多关于 here .

共享.py:

class Shared:
    def __init__(self):
        print("Init shared")

    def do_stuff(self, from_mod):
        print("Do stuff from {0}. I am instance {1}".format(from_mod, self))

shared = Shared()

foo.py

import shared

shared.shared.do_stuff("foo")

酒吧.py

import foo
import shared

shared.shared.do_stuff("bar")

如果我们执行 bar.py,我们得到:

>>> Init shared
>>> Do stuff from foo. I am instance <shared.Shared instance at 0x10046df38>
>>> Do stuff from bar. I am instance <shared.Shared instance at 0x10046df38>

因此,在您的情况下,您可以从任何地方引用 database_module 并且它只会初始化一次,因此可以有效地共享您的连接。

关于python - 在模块之间共享资源的良好做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13642654/

相关文章:

python - 使用正则表达式提取文件路径并将其保存在python中

python - 如何处理子组帮助消息

java - 使用 OpenJDK 14 java 模块运行时时 TLS 1.3 握手失败

linux - GDB 找不到行号

Python super 方法: class name not defined

spring - 无法找到 Spring Data JPA 的 Spring XML Schema 命名空间异常(仅在部署时!)

python - pandas 根据其他两列的值复制和编辑 'n' 行

python - 为 Pandas 数据框中的下一个连续行添加新列

perl - Perl 包/模块的返回值处理

python - Kubernetes:如何使用 python api 获取命名空间中的所有 pod?