sorteddict PEP proposal [started off as orderedict]

Paul Hankin paul.hankin at gmail.com
Thu Sep 27 00:44:16 CEST 2007


On Sep 26, 9:52 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Paul Hankin <paul.han... at gmail.com> wrote:
> >> So should Duncan's
>
> >>     def __removekey(self, key):
> >>         if key in self.__addkeys:
> >>             del self.__addkeys[key]
> >>         else:
> >>             self.__delkeys.add(key)
>
> >> be changed to:
>
> >>     def __removekey(self, key):
> >>         if key in self.__addkeys:
> >>             del self.__addkeys[key]
> >>         self.__delkeys.add(key)
>
> > Yes, and the same in __addkey: if it's in __delkeys it should be
> > removed from there, and added to __addkeys. There's an invariant: any
> > key is in at most one of __addkeys and __delkeys.
>
> No, don't do that. The code was fine as I had written it, except for the
> minor point that sets don't support 'del'! Also there need to be some tests
> which actually exercise those two branches of the code: once you add
> appropriate tests it will become obvious that you really do need the else.
>
> A key which is in dict must be either in __keycache or in __addkeys, but
> never in both.

Yes, I'm sorry: you're right.

But there's a different bug: if you delete a key that's not in the
dict, you'll add it to the deleted list before the exception for the
missing key is raised.

sd = sorteddict.sorteddict()
sd['a'] = 'a'
print sd.keys() = ['a']
try:
    del sd['b']
except:
    pass
sd['b'] = 'b'
print sd.keys()

The second print statement produces ['a'] rather than ['a', 'b']

--
Paul Hankin




More information about the Python-list mailing list