Python: global module lifetimes

I have a shared resource with a high initialization cost, and therefore I want to access it through the system (it is used for some tools mainly, therefore it should be easy). Therefore, I created a module that controls the configuration and access to it. It performs lazy initialization of the resource and stores it in the global variable of the module. Then I use the functions of this module in the system to work with the resource.
“Now I wonder (or how often) will I have to reinitialize the resource?”
- I know that objects are garbage collected in CPython (or better around) a zero reference counter, but stored in a module counted as a link, even if the module is not currently running?

Code example: here we have a module where _connect () is slow. I want to use report_safely () on my system and end up calling _connect () as little 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() 
+4
source share
2 answers

Objects that are no longer referenced are actually garbage collected (they are automatically deleted when their number of links drops to 0).

However, the module, global, will never have the value count count count count to 0; after importing the module object (its namespace), lives in the sys.modules . The namespace itself refers to your object.

In other words, your object lives forever until you remove it from the module namespace, do not delete the module namespace itself ( del sys.modules['yourmodule'] ) or the outputs of the python script.

+8
source

If the module containing the global one is in scope from the beginning to the end, then the global values ​​will correspond. You can be cleaner to use an instance of the class.

0
source

Source: https://habr.com/ru/post/1488112/


All Articles