[Python-ideas] Syntax for key-value iteration over mappings

Ron Adam ron3200 at gmail.com
Tue Jul 28 17:26:12 CEST 2015

On 07/28/2015 05:46 AM, Stephen J. Turnbull wrote:
> Nick Coghlan writes:
>   > Looking up the original iterator PEP shows it was done to enforce the
>   > container invariant "for x in y: assert x in y".
> I would argue that in the context of a given mapping, <key> and
> [<key>, <value>] are equivalent when <value> is <map>[<key>], so that
> we shou ld have the signature __contains__(self, key, value=self[key]),
> which is a NameError, but the intent should be obvious.

If keys were an actual objects, with a binding to a value, then I think 
they would be equivalent.  But I don't think we can change dictionaries to 
use them.

Having a Key objects might not be a bad addition on it's own.  It's a 
fundamental data object (like a lisp pair) that may be useful for creating 
other data objects.  It would be like a named tuple except the value is 
mutable.  And direct comparisons are done on the immutable key, not the 
mutable value.

It may be possible to do...

     for key in a_set:
         assert key in a_set
         print(key.name, key.value)


     for key in a_set:
         key.value = next(data)


     for key in a_dict:
        a_dict[key] = next(data)

I think the set version is easier to read and understand, but the dict 
version is probably faster and more efficient.

If there was a syntax for defining a key...
      {name:value, ...}    Oops dict, not set. ;-)
      {name:=value, ...}    set of keys?


More information about the Python-ideas mailing list