Creating "virtual" module-namespace

Robin Munn rmunn at pobox.com
Fri Dec 13 15:34:45 EST 2002


Harald <simon.12.ghum at spamgourmet.com> wrote:
> 
> So I know: I need an object only to form a namespace which I can access 
> via "."
> 
> I think it would be possible to use something else instead of an 
> object...
> 
> Do something like
> 
> zoo=[] # empty list
> exec a in zoo.__dict__  # execute a in the namespace of "zoo" 

You have the right idea, but using a list wouldn't work. Look at this:


Python 2.2.2 (#1, Nov  7 2002, 10:43:44)
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo: pass
...
>>> f = Foo()
>>> dir(f)
['__doc__', '__module__']
>>> f.__dict__
{}
>>> f.x = '1'
>>> f.__dict__
{'x': '1'}
>>> dir(f)
['__doc__', '__module__', 'x']
>>> l = []
>>> dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__str__', 'append',
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']
>>> l.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  AttributeError: 'list' object has no attribute '__dict__'
>>>


See how the object created from an empty class has so little names
already in its namespace? If you use a list, you're getting a namespace
already cluttered with names like 'append', 'insert', and 'sort'. Some
of these might be names you want for other functions. Using an object
that's an instance of an empty class is the best way to create a totally
empty namespace.

Besides, as you can see from the attempt to fetch l.__dict__, Python
lists aren't provided with a namespace hook via a __dict__ attribute. In
fact, none of the built-in types (list, dict, tuple...) have __dict__
attributes. So you have two choices:

1) Create an empty dictionary:

    my_namespace = {}
    exec 'spam = "eggs"' in my_namespace
    print my_namespace['spam']

   This approach requires dictionary notation to reference its contents.


2) Create an instance of an empty class:

    class Empty: pass
    my_namespace = Empty()
    exec 'spam = "eggs"' in my_namespace.__dict__
    print my_namespace.spam

   This approach requires namespace notation (via the period operator).


Both of these approaches are easy to use and will do what you need; it's
just a matter of whether you think my_namespace['spam'] looks better or
worse than my_namespace.spam for what you're trying to do.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838



More information about the Python-list mailing list