[Python-3000] Iterators for dict keys, values, and items == annoying :)

Ian Bicking ianb at colorstudy.com
Thu Mar 23 21:06:57 CET 2006


Jim Fulton wrote:
> Looking over some of the messages in the archives, I saw a reference
> to making dict keys, items, and values methods return iterators.  I've heard
> Guido mention this in the past.

I saw this too in the archives, and thought shit, that's going to mess 
up a lot of my code.  I would assume (though it's a separate point of 
discussion) that Python 3k should still try hard to keep backward 
compatibility.  Backward compatibility isn't a requirement, but it's 
still clearly a feature.

For an instance of code that would be broken:

   for key in d.keys():
       if something(key):
           del d[key]

If I didn't want a list, I probably would have iterated over d, wouldn't 
I?  Items is a little fuzzier, but I do a lot of:

   items = d.items()
   items.sort()

Not as big an issue, because these days I can already do 
sorted(d.items()) for the same effect.  Still, the change doesn't seem 
that interesting or useful to me, in comparison to the effect it will 
have on so much code.

One idea I had after reading a post of Brett's was a dual-use attribute; 
if you do d.keys you get an iterable (not an iterator, of course), and 
if you call that iterable you get a list.  This is backward compatible, 
arguably prettier anyway to make it a property (since there's no side 
effects and getting an iterable isn't expensive, the method call seems 
somewhat superfluous).

One can argue that this adds redundancy.

But anyway, a conceptual argument against .items() returning an 
iterator: .items() reads as a request for a concrete object to me.  That 
is, it doesn't read as "give me a promise that later you can give me the 
items from this object", it reads as "give me the items, right now and 
right here".  If it was a set-like object instead of a list, that'd be 
fine (maybe better -- avoid arbitrary ordering entirely).  But that's a 
separate conversation.



-- 
Ian Bicking  /  ianb at colorstudy.com  /  http://blog.ianbicking.org


More information about the Python-3000 mailing list