[Python-ideas] Syntax for key-value iteration over mappings
rosuav at gmail.com
Mon Jul 27 18:25:00 CEST 2015
On Tue, Jul 28, 2015 at 2:12 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> In effect, your suggestion makes the a:b syntax a "Do What I Mean"
> operation. It tries to gues whether you want to call expr.items() or
> enumerate(expr). Building DWIM into the language is probably not a good
I see what you mean. Yes, there's no easy way to iterate over either
type, but that isn't the point.
What my suggestion was positing was not so much DWIM as "iterate over
the keys and values of anything". A mapping type has a concept of keys
and values; an indexable sequence (list, tuple, etc) uses sequential
numbers as indices and its members as values. (A set might choose to
iterate this way by calling its members the indices, and using a fixed
True as the value every time.)
This would create a new iteration invariant. We currently have:
for x in y: assert x in y
With this, we would have:
for k:v in x: assert x[k] is v
And it should ideally raise an exception if this can't be done. (Which
currently would be the case for sets, so my suggestion above would
have to be accompanied by a set indexing definition that returns the
same fixed value for anything that's in it - something like "def
__getitem__(self, item): return item in self".)
Now, I'm still not saying this is a *good* idea. But I do think it's
Note that a simple definition using enumerate() would violate the
assertion, as you could use this to iterate over a non-sequence and
get indices and values. I'm not sure whether it's better to promise a
simple invariant (ie non-sequences should raise TypeError if used in
this way), or to adopt the stance of practicality and permit this.
Both make sense.
More information about the Python-ideas