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?
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 = Nonedef _connect():global __metricsclient = SomeSlowToSetUpClient()__metrics = SomeMetrics(client)client.connect()def report_safely():if not __metrics:_connect()__metrics.execute_lightweight_code()