Python:模块全局变量的生命周期 [英] Python: Lifetime of module-global variables

查看:490
本文介绍了Python:模块全局变量的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个共享资源,且初始化成本很高,因此我想在整个系统中访问它(它基本上用于某些仪器,因此必须轻巧).因此,我创建了一个模块来管理设置和对其进行访问.它对资源进行延迟的初始化,并将其存储在模块全局变量中.然后,我将在整个系统中使用此模块的功能来对资源进行操作.
-现在我想知道是否(或多久)必须重新初始化资源?
-我知道对象是在CPython上零引用计数(或更佳)上被垃圾回收的,但是即使模块当前没有执行,也存储在模块中作为引用计数吗?

I have a shared resource with high initialisation cost and thus I want to access it across the system (it's used for some instrumentation basically, so has to be light weight). So I created a module managing the setup and access to it. It does a lazy initialise of the resource and stores it in a module global variable. I then use functions of this module across the system to operate on the resource.
- Now I am wondering whether (or how often) I will have to reinitialise the resource?
- I know objects are garbage collected in CPython on (or better around) zero reference count, but is storing in an module counted as a reference, even if the module is not being executed at the moment?

代码示例:这是我们的模块,其中_connect()很慢.我想在整个系统中使用report_safely(),并最终尽可能少地调用_connect().

Example with code: here we have the module, where _connect() is slow. I want to use report_safely() across my system and end up calling _connect() as seldom as possible.

__metrics = None


def _connect():
    global __metrics

    client = SomeSlowToSetUpClient()
    __metrics = SomeMetrics(client)
    client.connect()


def report_safely():
       if not __metrics:
           _connect()

       __metrics.execute_lightweight_code()

推荐答案

不再引用的对象确实被垃圾回收(当它们的引用计数降至0时,它们将被自动删除).

Objects that are no longer referenced are indeed garbage collected (they are deleted automatically when their reference count drops to 0).

但是,全局模块永远不会将其引用计数降至0;导入模块对象(其命名空间)后,将驻留在sys.modules映射中.命名空间本身是指您的对象.

A module global, however, will never have it's reference count drop to 0; once imported a module object (its namespace), lives in the sys.modules mapping. The namespace itself refers to your object.

换句话说,您的对象永远存在,直到您从模块名称空间中将其删除,删除模块名称空间本身(del sys.modules['yourmodule'])或python脚本退出为止.

In other words, your object lives on forever, until you either delete it from the module namespace, delete the module namespace itself (del sys.modules['yourmodule']) or your python script exits.

这篇关于Python:模块全局变量的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆