在模块之间共享资源的好习惯? [英] Good practice sharing resources between modules?
问题描述
我正在重组我的代码,因此创建了新的命名空间.我正在更改模块的静态"类(每个方法中带有 @staticmethod 的类).这是要走的路,对吗?
问题是我对如何在这些模块之间共享资源有疑问.
假设我有一个模块,我正在从该模块执行与数据库的所有连接,当然所有类/方法都共享存储数据库游标的变量(我正在使用 SQLite).现在,在不同的模块中,它们也必须共享光标.
所以,我的想法:
在每个模块中声明全局变量.但是全球性是邪恶的,会吃掉孩子并抢走我们的工作.所以我不知道这是不是要走的路.
'''子模块1'''全局数据库_cursor
导入带有原始 database_cursor 的父"database_module 并使用如下内容:
'''子模块1'''db_cursor = database_module.database_cursor
在这种情况下,这一秒看起来不错,但我认为在许多情况下会导致递归导入,我想这是应该避免的.
您的第二种方法是可行的方法.Python 导入本质上是单例的.当一个模块被多次导入时,它只会在第一次被执行.后续导入从全局变量中获取模块对象实例.在此处了解更多相关信息.
shared.py:
class 共享:def __init__(self):打印(初始化共享")def do_stuff(self, from_mod):打印(从{0}做事.我是实例{1}".格式(from_mod,self))共享 = 共享()
foo.py
导入共享shared.shared.do_stuff("foo")
bar.py
import foo导入共享shared.shared.do_stuff("bar")
如果我们执行 bar.py 我们得到:
<预><代码>>>>初始化共享>>>从 foo 做东西.我是实例因此,在您的情况下,您可以从任何您想要的位置引用 database_module
并且它只会初始化一次,因此可以有效地共享您的连接.
I am reorganizing my code and therefore creating new namespaces. I'm changing "static" classes (classes with @staticmethod in each method) for modules. This is the way to go, right?
The problem is that I have doubts on how to share the resources between these modules.
Let's say I had a module from which I was doing all connections to database, and of course all classes/methods were sharing the variable which stored the DB cursor (I'm using SQLite). Now, in different modules, they also have to share the cursor.
So, my ideas:
Declare the global variable in each module. But globals are evil, eat children and steal our jobs. So I don't know if this is the way to go.
'''Sub Module 1''' global database_cursor
Import the "father" database_module with the original database_cursor and use something like this:
'''Sub Module 1''' db_cursor = database_module.database_cursor
This second looks fine in this case, but I think in many cases will lead to recursive imports, which I guess it´s something to avoid.
Your second method is the way to go. Python imports are singleton by nature. When a module is imported multiple times it is only executed the first time. Subsequent imports fetch the module object instance from the globals. More on that here.
shared.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")
bar.py
import foo
import shared
shared.shared.do_stuff("bar")
If we execute bar.py we get:
>>> 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>
So in your case you can reference database_module
from anywhere you want and it gets initialized only once, therefore effectively sharing your connection.
这篇关于在模块之间共享资源的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!