Skip to main content
 首页 » 编程设计

python之如何初始化长生命周期变量

2024年10月25日9lyj

我从 C# 和 Java 开始第一次涉足 Python。到目前为止还不错,但我似乎无法理解的一个概念是如何初始化将在许多模块和包中使用的长生命周期变量?

在 C# 中,我可以有一个 Environment 或 Config 类,它们在应用程序启动时实例化并通过依赖注入(inject)或其他可以保存值的机制传递。

作为一个具体示例,我正在使用 SQLAlchemy 执行我的数据库插入。我创建了一个模块 db.py,其中的数据库代码如下所示:

engine = create_engine('dburl', echo=True) 
 
conn = engine.connect() 
 
metadata = MetaData() 
 
table_mytable = Table('mypackage', metadata, 
    Column('id', String, primary_key=True), 
    Column('mystuff', String), 
 
ins = table_mytable.insert()     
 
def insert(): 
    result = conn.execute(ins) 

然后其他代码导入我的 db 模块并使用 insert 函数进行插入。

我遇到的问题是,每次我导入我的数据库模块以供使用时,engine、conn、metadata 和 table_my_table 变量被重新创建,所以基本上每次导入我都重新连接到 db 并重新定义所有元数据?

这是正确的和预期的事情吗?还是有更好的方法来解决这个问题?

请您参考如下方法:

What I am having trouble with is, everytime I import my db module for use, will the engine, conn, metadata and table_my_table variables be re-created so essentially for every import I am reconnecting to the db and re-defining all the meta data?

没有。 Python 缓存导入:导入一次的模块不会再次导入,而是重复使用导入的模块。

您可以通过将 test.py 放在某个目录中来验证这一点:

print("foo") 

并启动一个 python 解释器:

>>> import test 
foo 
>>> import test 

您会注意到代码只运行一次。

Or is there a better way to approach this?

因此,拥有模块全局变量是保持整个程序运行需要保持状态的有效方法。