[Python-ideas] __iter__(), keys(), and the mapping protocol

Alex Walters tritium-list at sdamon.com
Mon Sep 10 23:50:24 EDT 2018


I can see custom mapping types where iterating the keys() would be trivial, but items() could be expensive.  I could use that as an argument, but I don't have to. The keys() method is part of the API, just like index() and count() are part of the sequence API.  To be treated like a mapping everywhere, python requires that you define* a keys() method, so why not use it?  I don't see anything wrong with python using "public" methods, in this context.


* If you use ABCs, then you don't need to define keys(), but that’s a tangent.

> -----Original Message-----
> From: Python-ideas <python-ideas-bounces+tritium-
> list=sdamon.com at python.org> On Behalf Of Elias Tarhini
> Sent: Monday, September 10, 2018 10:04 PM
> To: Python-Ideas <python-ideas at python.org>
> Subject: [Python-ideas] __iter__(), keys(), and the mapping protocol
> 
> This has been bouncing around in my head for a while regarding the requisite
> keys() method on mappings:
> 
> How come the ** unpacking operator, a built-in language feature, relies on a
> non-dunder to operate?
> 
> To me, I mean to say, requiring that classes implement keys() – a method
> whose name is totally undistinguished – in order to conform to the mapping
> protocol feels like a design running counter to Python's norm of using
> dunders for everything "hidden". I am not sure if it feels dirty to anybody
> else, however. Interestingly, the docs already say
> <https://docs.python.org/3/reference/datamodel.html#object.__iter__>
> that [f]or mappings, [__iter__()] should iterate over the keys of the
> container, but it of course is not enforced in any way at present.
> 
> 
> So, then — how about enforcing it? Should __iter__(), for the reasons
> above, replace the current purpose of keys() in mappings?
> 
> 
> I'm not properly equipped at the moment to mess around with CPython
> (sorry), but I assume at a minimum this would entail either replacing all
> instances of PyMapping_Keys() with PyObject_GetIter() or alternatively
> changing  PyMapping_Keys() to call the latter.
> 
> 
> Does it sound like a reasonable change overall?
> 
> 
> Eli



More information about the Python-ideas mailing list