namespace dictionaries ok?

Ron Adam rrr at ronadam.com
Wed Oct 26 19:44:50 EDT 2005



Alex Martelli wrote:

> Ron Adam <rrr at ronadam.com> wrote:
>    ...
> 
>>     class namespace(dict):
>>         def __getattr__(self, name):
>>             return self.__getitem__(name)
> 
>    ...
> 
>>Any thoughts?  Any better way to do this?
> 
> 
> If any of the keys (which become attributes through this trick) is named
> 'update', 'keys', 'get' (and so on), you're toast; it really looks like
> a nasty, hard-to-find bug just waiting to happen.  If you're really
> adamant on going this perilous way, you might try overriding
> __getattribute__ rather than __getattr__ (the latter is called only when
> an attribute is not found "in the normal way").

Thanks Alex, I was wondering what the difference between __getattr__ and 
  __getattribute__ was.


> If you think about it, you're asking for incompatible things: by saying
> that a namespace X IS-A dict, you imply that X.update (&c) is a bound
> method of X; at the same time, you also want X.update to mean just the
> same thing as X['update'].  Something's gotta give...!-)
> 
> Alex

Part of the motivation of this is to try and keep names as names and 
data as data in my programs.  I would use dictionaries for data storage, 
and namespace_dicts for strictly name/value passing.  So some 
limitations with names are expected just as they would exist anywhere 
else with object names.  Ie.. can't use keywords, and using names of 
methods can cause objects to break, etc...

This seems to be the closest to a generic namespace object so far.

class namespace(dict):
     __getattribute__ = dict.__getitem__
     __setattr__ = dict.__setitem__
     __delattr__ = dict.__delitem__

Not having any public and/or visible methods of it's own is a good thing 
here.  So you would need to use dict.update(A_namespace, A_dict) in this 
case.  I don't think thats a problem.  Maybe a namespace object, (as I 
am thinking of it), should not have it's own interface, but inherit one 
from the object it's inserted into?

Anyway... this is experimental, and not production code of any sort. ;-)

Cheers,
    Ron




More information about the Python-list mailing list