import - How to detect or prevent multiple instances of the same modules in Python? -


in short: in python easy create multiple instances of same module, each instance having own set of global variables.

i need add check module detect such multiple instantiation , raise exception.

my problem same one: module imported multiple times

this smallest directory structure reproduce problem:

/test/a/__init__.py  /test/a/aa.py: print "aa: __name__: ", __name__  /test/b/b.py: import aa import aa 

then

export pythonpath=/test:/test/a python /test/b/b.py 

prints:

aa: __name__:  a.aa aa: __name__:  aa 

so, module aa.py imported twice different names.

needless module aa.py 2 sets of global variables, screws logic inside module.

of course, in trivial example above easy detect error eyes, in complex project multiple subdirectories, these errors keep popping regularly.

so, need global variable or process-wide store or that. idea?

edit: bibhas asked example of multiple instances of same global variable. here is:

/test/a/__init__.py  /test/a/aa.py: print "aa: __name__: ", __name__  import thread import time  test_var = __name__  def test():     in range(0,5):         print "aa thread: test_var: ", test_var         time.sleep(1)  thread.start_new_thread( test, () )  /test/b/b.py:  print "b: __name__: ", __name__  import aa import aa  import time time.sleep(10) 

now running

export pythonpath=/test:/test/a python /test/b/b.py 

prints:

aa: __name__:  a.aa aa: __name__:  aa aa thread: test_var:  aa aa thread: test_var:  a.aa aa thread: test_var:  aa aa thread: test_var:  a.aa ... 

so, clear there 2 instances of variable test_var. if try implement singleton in module, there 2 instances of singleton, etc.

edit2: so, solution suggested guy l like:

/test/a/aa.py: import os if "aa.py" in os.environ:     raise exception("duplicate instantiation of aa.py") os.environ["aa.py"] = __name__ 

it seems work ok (as long not call import on multiple threads). have better one?

it's ugly workaround can use os.environ[] set enviorment variables. don't since contaminates eviroment variables.

here how can set those: http://code.activestate.com/recipes/159462-how-to-set-environment-variables/

good luck, guy


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -