On Fri, Feb 21, 2014 at 9:25 PM, Yury Selivanov email@example.com wrote:
On 2/21/2014, 10:42 PM, Chris Angelico wrote:
That fixes it for the list. Square brackets notation works for any sequence. Are you proposing adding magic to the language so that any class that defines a __getitem__ automatically has a .get() with these semantics? Or, conversely, that defining __getitem__ requires that you also explicitly define get()?
No, I proposed to consider adding 'list.get()' and 'collections.abc.Sequence.get()' (or a better name), if catching IndexError is such a popular pattern.
We can also fix stdlib. Authors of the python libraries/ frameworks will likely follow.
No magic in the language, no requirements on __getitem__, obviously.
We could also add a companion to getattr: getitem().
def getitem(seq, index, default=_NOT_SET): try: return seq[index] except IndexError: if default is _NOT_SET: raise return default
Of course, one might expect getitem() to work for mappings too (or we'd have 2 distinct functions for mappings and sequences). Having getitem() work for both would not be too hard.
Keep in mind that I still think that the PEP 463 syntax is worth adding more than any getitem() function. However, I think the getitem() route would be better than adding another method to sequences (including list).