1st Sketch at at ReadOnly dict

Charles Hixson charleshixsn at earthlink.net
Mon Jan 20 22:30:23 EST 2014


On 01/20/2014 04:08 PM, Chris Angelico wrote:
> On Tue, Jan 21, 2014 at 7:09 AM, Charles Hixson
> <charleshixsn at earthlink.net> wrote:
>> #    @note Instances can be created only from existing dicts.
>>
>>      ##    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
> Instead of demanding that a dict (or dict subclass) be passed, why not
> simply pass all args on to dict() itself? Is there a reason this won't
> work?
>
> def __init__(self, *args, **kwargs):
>      self._ddict = dict(*args, **kwargs)
>
> ChrisA
It would work, as long as it would work for dict(), but I have been 
expecting to use it in situations where it would be useful to have a 
different access to the dict that would be writeable.  So I didn't 
bother.  (Well, and took steps to ensure that it was being used in the 
manner that I expected.  So I'd know to change it if it were 
appropriate.)  It *would* make it more difficult for the class to test 
it's creation arguments for sanity, though.  (One could argue that 
allowing read only access to an empty dict is violating sanity, but I 
don't think in any dangerous way.)  I do sometimes worry that using 
isinstance excessively is overly expensive.  Perhaps I should wrap them 
with a test for debug mode.


-- 
Charles Hixson




More information about the Python-list mailing list