[Python-3000] Spooky behavior of dict.items() and friends
Paul Moore
p.f.moore at gmail.com
Wed Apr 2 00:25:50 CEST 2008
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.
Paul.
More information about the Python-3000
mailing list