empty classes as c structs?

Steven Bethard steven.bethard at gmail.com
Wed Feb 9 18:26:26 EST 2005


Alex Martelli wrote:
> Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> 
> 
>>>We could use __add__, instead for combining namespaces
>>
>>Update already let's us combine namespaces. To create a new object that merges
>>two namespaces do:
>>   namespace.update(namespace(ns_1), ns_2)
> 
> 
> One thing I'd like to see in namespaces is _chaining_ -- keeping each
> namespace separate but having lookups proceed along the chain.  (The
> best semantics for _bindings_ as opposed to lookups isn't clear though).

I'm not sure I understand exactly what you're looking for here...  Is 
this what you want?

py> b = Bunch.chain(Bunch(x=1), Bunch(x=2, y=2), Bunch(y=3))
py> b.x
1
py> del b.x
py> b.x
2
py> del b.x
py> b.x
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "D:\Steve\My Programming\python\bunch.py", line 104, in 
__getattribute__
     raise AttributeError(name)
AttributeError: x
py> b.y
2
py> del b.y
py> b.y
3
py> del b.y
py> b.y
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "D:\Steve\My Programming\python\bunch.py", line 104, in 
__getattribute__
     raise AttributeError(name)
AttributeError: y

Or should 'del b.x' remove all 'x' attributes from all the bunches in 
the chain?


The code I used for this looks like:

class Bunch(object):
     ...
     class chain(object):
         def __init__(self, *bunches):
             self._bunches = bunches
         def __getattribute__(self, name):
             getattribute = super(Bunch.chain, self).__getattribute__
             try:
                 return getattribute(name)
             except AttributeError:
                 for bunch in getattribute('_bunches'):
                     try:
                         return getattr(bunch, name)
                     except AttributeError:
                         pass
                 raise AttributeError(name)
         def __delattr__(self, name):
             for bunch in self._bunches:
                 try:
                     return delattr(bunch, name)
                 except AttributeError:
                     pass
             raise AttributeError(name)

I didn't know what to do for __setattr__...  Was that what you meant by 
"The best semantics for _bindings_ as opposed to lookups isn't clear 
though"?

Steve



More information about the Python-list mailing list