Pointers

Richard Jones Richard.Jones at fulcrum.com.au
Fri Mar 17 01:22:49 CET 2000


[Curtis Jensen]
> I need a slightly different twist now.  Somthing like:
> 
> >>> d = {'A':0,'B':0}
> >>> c = {'A': -> (Pointer to) d['A']}
> >>> print c['A']
> 0
> >>> d['A'] = 10
> >>> print c['A']
> 10

   You are asking far too much of the standard dictionary type :)

   You'll either need to use one of the hacks described by other posters which 
involves using a mutable proxy entry for the dictionary items - such as a list 
or an instance or a proxy class of your own rolling. The other option that's 
immediately obvious to me is for you to extend the dictionary class (via 
UserDict) to provide the semantics you're after.

   Actually, the proxy class is a kinda neat idea and was hinted at by another 
poster (though I've lost that post now):

>>> class Pointer:
...  def __init__(self, dict, item):
...   self.dict = dict
...   self.item = item
...  def __getattr__(self, attr):
...   if attr == 'value':
...    return self.dict[self.item] 
...   raise AttributeError, attr
...  def __setattr__(self, attr, value):
...   if attr == 'value':
...    self.dict[self.item] = value
...   else:
..    self.__dict__[attr] = value
... 
>>> d = {'A':0,'B':0}
>>> a = {'A': Pointer(d, 'A')}
>>> print a['A'] 
<__main__.Pointer instance at 80d8e60>
>>> print a['A'].value
0
>>> d['A'] = 10
>>> print a['A'].value
10
>>> a['A'].value = 20
>>> print d['A']
20
>>> 


    At this point, I'd be taking a serious look at your actual requirements and 
debating whether builtin dictionaries are really what you want to be using. 
You've got complete freedom to create any type of class you need - don't limit 
your thinking by sticking to the builtin types!



        Richard






More information about the Python-list mailing list