multiple namespaces within a single module?
Ethan Furman
ethan at stoneleaf.us
Thu Feb 9 16:12:42 EST 2012
Peter Otten wrote:
> jkn wrote:
>
>> is it possible to have multiple namespaces within a single python
>> module?
>
> Unless you are abusing classes I don't think so.
Speaking of...
<code>
class NameSpace(object):
def __init__(self, globals):
self.globals = globals
self.current_keys = list(globals.keys())
def __enter__(self):
return self
def __exit__(self, *args):
new_items = []
for key, value in self.globals.items():
if key not in self.current_keys and value is not self:
new_items.append((key, value))
for key, value in new_items:
setattr(self, key, value)
del self.globals[key]
if __name__ == '__main__':
with NameSpace(globals()) as a:
def function():
print('inside a!')
with NameSpace(globals()) as b:
def function():
print('inside b!')
a.function()
b.function()
print(vars())
</code>
The NameSpace objects do *not* get their own copy of globals(), but for
functions, etc., it should work fine. As a bonus the above code works
for both 2.x and 3.x.
~Ethan~
More information about the Python-list
mailing list