multiple namespaces within a single module?

Ethan Furman ethan at stoneleaf.us
Fri Feb 10 01:05:41 CET 2012


Ethan Furman wrote:
> Hrm -- and functions/classes/etc would have to refer to each other that 
> way as well inside the namespace... not sure I'm in love with that...


Not sure I hate it, either.  ;)

Slightly more sophisticated code:

<code>
class NameSpace(object):
     def __init__(self, current_globals):
         self.globals = current_globals
         self.saved_globals = current_globals.copy()
     def __enter__(self):
         return self
     def __exit__(self, *args):
         new_items = []
         for key, value in self.globals.items():
             if (key not in self.saved_globals and value is not self
                     or key in self.saved_globals
                     and value != self.saved_globals[key]):
                 new_items.append((key, value))
         for key, value in new_items:
             setattr(self, key, value)
             del self.globals[key]
         self.globals.update(self.saved_globals)

if __name__ == '__main__':
     x = 'inside main!'
     with NameSpace(globals()) as a:
         x = 'inside a?'
         def fn1():
             print(a.x)
     with NameSpace(globals()) as b:
         x = 'inside b?'
         def fn1():
             print(b.x)
         def fn2():
             print('hello!')
             b.fn1()
     y = 'still inside main'
     a.fn1()
     b.fn1()
     print(x)
     print(y)
</code>

~Ethan~



More information about the Python-list mailing list