Good practice sharing resources between modules?

I will reorganize my code and therefore create new namespaces. I am changing the “static” classes (classes with @staticmethod in each method) for the modules. This is the way, right?

The problem is that I doubt how to allocate resources between these modules.

Let's say I have a module from which I made all database connections, and, of course, all classes / methods shared a variable that stored the DB cursor (I use SQLite). Now, in different modules, they also need to share a cursor.

Graphical representation of dependences

So my ideas are:

  • Declare a global variable in each module. But globals are evil, they eat children and steal our jobs. So I don’t know if this is suitable.

    '''Sub Module 1''' global database_cursor 
  • Import the father database with the original database_cursor property and use something like this:

     '''Sub Module 1''' db_cursor = database_module.database_cursor 

In this case, it looks good, but I think that in many cases it will result in recursive imports, and I think that this cannot be avoided.

+7
source share
1 answer

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.

+8
source

All Articles