Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #64380
| Date | 2014-01-20 15:37 -0800 |
|---|---|
| From | Charles Hixson <charleshixsn@earthlink.net> |
| Subject | Re: 1st Sketch at at ReadOnly dict |
| References | <52DD8297.9050504@earthlink.net> <lbk29u$oho$1@ger.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.5763.1390261121.18130.python-list@python.org> (permalink) |
On 01/20/2014 12:52 PM, Peter Otten wrote:
> Charles Hixson wrote:
>
>> This is just a first sketch, and I haven't yet attempted to test it, so
>> what I'm hoping for is criticisms on the general approach.
>>
>> class RODict:
>> def __init__ (self, ddict = {}):
> Default values are evaluted just once when the method is created. Mutable
> default values mean trouble:
>
>>>> class D:
> ... def __init__(self, dict={}):
> ... self.dict = dict
> ... def __setitem__(self, key, value):
> ... self.dict[key] = value
> ... def __repr__(self): return repr(self.dict)
> ...
>>>> d1 = D()
>>>> d2 = D()
>>>> d1[1] = 42
>>>> d2[2] = 42
>>>> d1
> {1: 42, 2: 42}
>>>> d2
> {1: 42, 2: 42}
>
>> if not isinstance(ddict, dict):
>> raise TypeError("ddict must be a dict. It is " +
>> repr(ddict))
>> self._ddict = ddict
> I think instead of the type check I would build a new dict from the
> argument. The usual initializers
>
> dict({1:2, 3:4})
> dict([(1,2), (3,4)])
> dict(a=1, b=2)
>
> should work with your read-only dict.
>
>> ## Test for containment.
>> # @param key The item to be found.
>> # @return True If key is in the instance, otherwise False.
> Docstrings are usually prefered over comments like the above.
>
>> def __contains__(self, key):
>> return key in self._ddict
> Did you know
>
> http://docs.python.org/dev/library/collections.abc.html#collections.abc.Mapping
>
> Subclass from it to ensure that all the usuall methods are defined.
>
That link,
http://docs.python.org/dev/library/collections.abc.html#collections.abc.Mapping
, is a very good one. I hadn't realized that it separated Mapping from
MutableMapping.
It would be nice if there were some examples of it's usage around,
though. I can't really tell how to use it. (E.g., it mixes in
__contains__, but it doesn't show how to specify what you are testing
for cotainment in. So it looks as if I need to specify everything
anyway because I can't tell what might be implemented in some
inappropriate way.) OTOH, it's a good list of what needs to be
implemented. (I see that I left out implementation of eq and ne, which
is pretty straightfoward, but apparently needed (unless it's
automatically being handled by the mixin...which I can't tell).
--
Charles Hixson
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: 1st Sketch at at ReadOnly dict Charles Hixson <charleshixsn@earthlink.net> - 2014-01-20 15:37 -0800
csiph-web