[Python-3000] Spooky behavior of dict.items() and friends

Benjamin Peterson musiccomposition at gmail.com
Wed Apr 2 00:53:01 CEST 2008


On Tue, Apr 1, 2008 at 5:25 PM, Paul Moore <p.f.moore at gmail.com> wrote:

> On 01/04/2008, "Martin v. Löwis" <martin at v.loewis.de> wrote:
> > > What really bugs me about this state of affairs is that I consider the
> >  > python 2 dict.items() to be safe and free of surprises, but I no
> >  > longer feel the same way about it in 3; this is really about the fact
> >  > that when you want to get the items, keys, or values of a dict, the
> >  > simplest thing is no longer the safest thing. (I don't want to
> belabor
> >  > this point too much since it isn't really my place to judge, but to
> >  > me, dict views feel like they are a "special case that breaks the
> >  > rules.")
> >
> >
> > I feel to the contrary. 2.x .keys() was not safe, but 3.x keys() is.
> >  When I iterate over the keys of a dictionary, I want all of them,
> >  and I want only the keys. With 2.x, it could always happen that the
> >  dictionary changes "behind me", and then I'd either iterate over
> >  not all of the keys, or see some keys that aren't actually in the
> >  dictionary anymore. With 3.x dictionary views, it's much safer now.
>
> The oddity with the 3.x keys() is that it's plausible to retain a
> reference to d.keys(), but if you do so it can change if you alter d.
> In 2.x, d.keys() is static and d.iterkeys() is (for all practical
> purposes) not something you retain. The 3.x d.keys() "action at a
> distance" is unfamiliar - I can't think of an example of this type of
> view semantics in 2.x (at least in the core - numpy has had this for
> some time, I believe).
>
> I suspect that view semantics will become less surprising over time,
> but I think it's a fair point that it's something new to get used to.

I personally find it less surprising. It seems logical to me that whatever
you get from dict.items should reflect the current state of the dictionary.
When you want it static, it's better to be explicit and say list(dict.keysor
dict.values).

>
>
> Paul.
> _______________________________________________
> Python-3000 mailing list
> Python-3000 at python.org
> http://mail.python.org/mailman/listinfo/python-3000
> Unsubscribe:
> http://mail.python.org/mailman/options/python-3000/musiccomposition%40gmail.com
>



-- 
Cheers,
Benjamin Peterson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20080401/3282c730/attachment-0001.htm 


More information about the Python-3000 mailing list