LGB
LGB

Reputation: 718

How can I set up global for every imported file in Python automatically?

I have a large python code with many modules and classes. I have a special class, whose single instance is needed everywhere throughout the code (it's a threaded application, and that instance of a class also holds Thread Local Storage, locks, etc). It's a bit uncomfortable to always "populate" that instance in every imported module. I know, using globals is not the best practice, but anyway: is there any "import hook" in python, so I can do with hooking on it to have my instance available in every modules without extra work? It should work for normal imports, "from mod import ..." too, and for import constructs too. If this is not possible, can you suggest a better solution? Certenly it's not fun to pass that instance to the constructors of every classes, etc ... Inheritance also does not help, since I have modules without classes, and also I need a single instance, not the class itself ...

class master():
    def import_module(self, name):
        mod = __import__(name)
        mod.m = self
        return mod
[...]
m = master()

Currently I am thinking something like that: but then I have to use m.import_module() to import modules, then other modules will have instance of master class with name of "m" available, so I can use m.import_module() too, etc. But then I have to give up to use "normal" import statements, and I should write this:

example_mod = m.module_import("example_mod")

instead of just this:

import example_mod

(but for sure I can do with this too, to assign "m" to example_mod.m then)

Upvotes: 2

Views: 180

Answers (2)

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

Certainly it's not fun to pass that instance to the constructors of every classes

You don't have to do this. Set up your global class in a module like config and import it

# /myapp/enviroment/__init__.py

class ThatSingleInstanceClass: pass

# create the singleton object directly or have a function init the module
singleton = ThatSingleInstanceClass() 



# /myapp/somewhere.py

# all you need to use the object is importing it
from myapp.enviroment import singleton

class SomeClass:

    def __init__(self): # no need to pass that object
        print "Always the same object:", singleton

Upvotes: 4

Daenyth
Daenyth

Reputation: 37441

What's wrong with having each module import the needed object? Explicit is better than implicit.

Upvotes: 2

Related Questions