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()
Zakum source share