1st Sketch at at ReadOnly dict

Charles Hixson charleshixsn at earthlink.net
Mon Jan 20 23:37:42 EST 2014


On 01/20/2014 08:14 PM, Dan Stromberg wrote:
> On Mon, Jan 20, 2014 at 12:09 PM, Charles Hixson
> <charleshixsn at earthlink.net> wrote:
>
>> class RODict:
>>      #Instance Variable Doc
>>      ##    @var    _ddict
>>      #        This variable holds the reference to the dict.
>>
>>      ##    Class initializer.
>>      #    @param    ddict    The data dictionary to which this is a read only
>>      #            access.
>>      #    @throws    TypeError if ddict is not a dict.
>>      def __init__ (self, ddict = {}):
>>          if not isinstance(ddict, dict):
>>              raise    TypeError("ddict must be a dict.  It is " +
>> repr(ddict))
>>          self._ddict    =    ddict
> When I see this isinstance, I think "Gee, that means none of the
> dict-like-objects I recently compared would work with this class."
>
> The comparison is at the URL below; all the things compared are trees
> that provide a dictionary-like interface, but also find_min, find_max
> and can iterate in key order.  I don't think any of them inherit from
> dict, but they are all dict-like in a duck-typed sense:
>
> http://stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/2014-01/
>
> HTH
>
Well, it would mean you couldn't create instances of this class from 
them.  I haven't yet specified the eq and ne methods, but they'd 
probably be something like:
def ne(self, key):
     return self._ddict.ne(key)
(I'd need to look up the precise names of the comparison routines. 
Perhaps it would be "__ne__" rather than "ne".)
So if they'd work with a normal dict, they should work with this, for 
comparison.

Note that this is a dict-alike, and therefore not in a predictable 
order.  If the items were to be ordered, however, they would be in order 
by the value rather than by the key, as my use-case is most likely to 
want to access the items with the highest value most often.   I may even 
decide to use a list of lists, but a dict yields simpler code, even if I 
suspect that lists might be more efficient. But the choice of list would 
mean I could use a tuple, which because it is standard would also tend 
to make things simpler.  (It wouldn't, however, allow background 
updating, as dictviews do, and also RODict does, so I'd need to find 
some way to manage that...probably meaning that I'd need to regenerate 
them more often.)

-- Charles Hixson



More information about the Python-list mailing list