The second way is the way. Python imports are individual. When a module is imported several times, it is executed only for the first time. Subsequent imports extract an instance of the module object from global variables. Read more about it here .
shared.py:
class Shared: def __init__(self): print("Init shared") def do_stuff(self, from_mod): print("Do stuff from {0}. I am instance {1}".format(from_mod, self)) shared = Shared()
foo.py
import shared shared.shared.do_stuff("foo")
bar.py
import foo import shared shared.shared.do_stuff("bar")
If we execute bar.py, we get:
>>> Init shared >>> Do stuff from foo. I am instance <shared.Shared instance at 0x10046df38> >>> Do stuff from bar. I am instance <shared.Shared instance at 0x10046df38>
Thus, in your case, you can refer to database_module from anywhere you want, and it is initialized only once, therefore it effectively splits your connection.
Rickya
source share