getitem() (was Re: [Python-Dev] PEP 463: Exception-catching expressions)
(in response to https://mail.python.org/pipermail/python-dev/2014-February/132648.html) On Fri, Feb 21, 2014 at 9:25 PM, Yury Selivanov <yselivanov.ml@gmail.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). -eric
On Sat, Feb 22, 2014 at 4:14 PM, Eric Snow <ericsnowcurrently@gmail.com> wrote:
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.
Very easy. Just catch LookupError or (IndexError, KeyError) instead of IndexError. ChrisA
participants (2)
-
Chris Angelico -
Eric Snow