Python gives two main tools for dealing with namespaces: modules and classes. Gribouillis pointed out how you can rearrange your modules to give you the access you want. This is a major consideration in any large project: how am I going to arrange my modules so they can communicate in the way I need them to? My first thought is to use classes, which I feel give you more control:
main.py:
from foo import Ien
from bar import Twa
class Main(object):
def __init__(self, modules = []):
self.a = 1
self.b = 2
self.modules = [module(self) for module in modules]
def act(self):
for module in self.modules:
module.act()
if __name__ == '__main__':
main = Main([Ien, Twa])
main.act()
foo.py:
class Ien(object):
def __init__(self, master):
self.master = master
def act(self):
self.master.c = 3
self.master.d = 4
bar.py:
class Twa(object):
def __init__(self, master):
self.master = master
def act(self):
for attr in ('a', 'b', 'c', 'd'):
try:
print('{} = {}'.format(attr, getattr(self.master, attr)))
except AttributeError:
print('{} mislearre'.format(attr))
The output from running main.py:
Output:
a = 1
b = 2
c = 3
d = 4
In a real program, Ien and Twa would be subclasses of a Module object that would provide some basic functionality, like the shared __init__. If the modules need to communicate with each other, they would look at self.master.modules to find the module to communicate with, and get a reference to the object from there. In that case you might want a different structure to Main.modules that would be easier to search (like a dict). You could also set that as an attribute of the individual modules during Main.__init__, so that it is easier to access. But I would only do that if the set of modules is going to be static. Another way to do it is to have helper methods that find the module that another module needs.
Note that namespaces for modules and classes are implemented as dictionaries. So you could probably figure out a way to implement this using just nested dictionaries. But it's easier to just use the higher level constructs of modules and classes.