Thought on PEP 204 and 276

phil hunt philh at comuno.freeserve.co.uk
Tue May 28 15:28:42 EDT 2002


On Tue, 28 May 2002 14:45:30 +0100, Steve Horne <steve at lurking.demon.co.uk> wrote:
>On Mon, 27 May 2002 21:33:47 +0200, holger krekel
><pyth at devel.trillke.net> wrote:
>
>>       for i,item in enumerate(somelist):
>>            # use item
>>            somelist[i]=newvalue
>
>Could enumerate(dictionary) be used to extract key, value pairs from a
>dictionary?
>
>I realise this duplicates the items() method, but it has the advantage
>of creating consistency between sequence and mapping types.
>
>Also, why wasn't an items() method simply added to sequence types,
>treating them as mapping types with an integer key?

That would seem to me the obvious way to do it.

People who've used Smalltalk will appreciate how it has a hierarchy 
of abstract superclasses for collections, including: 

   Collection - any collection

   KeyedCollection - any collection that can be accessed by a key

   IndexedCollection - any keyed collection where the keys are the 
      range of integers 0..n for some n.

To me, this makes sense, and it'd be nice if Python did it, if not 
in the actual classes, at least in them having the right interfaces.

KeyedCollection would expect its subclasses to define a keys() 
method, which returns all the keys, and would define methods 
such as has_key() and items() which call the keys() method:

class KeyedCollection:

   def has_key(self, k):
      return k in self.keys()

   def items(self):
      result = []
      for k in self.keys()
         result.append([k, self[k]])
      return result

   def get(self, k, default =None):
      if self.has_key(k):
         return self[k]
      else:
         return default

This would haver the benefit that if you define your own subclasses 
of KeyedCollection, you would only have to write a keys() method, 
and all the others already work -- or you could re-implement them 
for efficiency.


-- 
<"><"><"> Philip Hunt <philh at comuno.freeserve.co.uk> <"><"><">
<"><"><">   My website has moved -- new address is:  <"><"><"> 
<"><"><">    <http://www.comuno.freeserve.co.uk/>    <"><"><"> 



More information about the Python-list mailing list