I'm breaking up a large-ish (for me anyway!) project into 2 or 3 modules, including a 'main' module with the top level menu etc. It will import a two or three 'sub-modules' for different aspects of the application. However those modules will need various settings etc from the main module. Yes, they could be passed as arguments but there are quite a few of them and they are liable to change. Different modules will need different sub-sets of the settings.
I'd like to be able to have the subordinate modules simply 'reach back' for their settings as needed (sort of global across modules as it were).
Here is a mickie-mouse example of what I mean:
test1:
# dummy version of main / sub modules with mutual importing
# this is the 'main module'
# in this trivial example, it would be easy to make mode an argument of the function
# but as an alternatiove can test2 'reach back' to test1?
from test2 import taskA
mode = 1
ans = taskA()
print(ans)
test2:
# dummy version of main / sub modules with mutual importing
# this is the 'sub module' that executes taskA
from test1 import mode
def taskA():
print('taska, mode = {0}'.format(mode))
return 'Hello World!'
mode = 0
print('test2 initialised')
And the results is
Traceback (most recent call last):
File "C:\Python33\MyScripts\test1.py", line 6, in <module>
from test2 import taskA
File "C:\Python33\MyScripts\test2.py", line 4, in <module>
from test1 import mode
File "C:\Python33\MyScripts\test1.py", line 6, in <module>
from test2 import taskA
ImportError: cannot import name taskA
Presumably this is due to potential circularity. (Though, if its able to detect the circularity - not hard in this case!, ie that taskA has already been imported, you'd think its able to simply break out of the circularity, as opposed to throwing an error).
Is there a way to achieve this? There's several obvious ways to code around it - keep it as one module; pass the settings as arguments (but that will have pitfalls if 'test2' has to modify any of the settings, if only as Im still getting my head around python's handling of mutable objects and binding); move all the settings to a separate module (test0) accessed by both test1 and test2.
Given that these modules are intimately connected (I believe the term is strongly coupled), logically it should all be one module. Except that its getting big.
My question is twofold ... how best to do what I want; but also to understand why Python cant handle mutual imports.