On Wed, Jul 1, 2020 at 6:23 AM Christopher Barker <python...@gmail.com>
wrote:

> On Tue, Jun 30, 2020 at 8:55 PM David Lowry-Duda <da...@lowryduda.com>
> wrote:
>
>> On the other hand, it seems far more likely to miss keys in a dictionary
>> than it is to repeatedly mistake indices in a list.
>>
>
> exactly -- dict keys are arbitrary, and it's pretty common to store
> "sparse" data by simply leaving out the key if there's nothing interesting
> attached to it.
>
> But for Sequences, the only time you get an index error is if you are
> indexing beyond the length of the list, and the only case I can think of
> for get() would be for a maybe-empty list. otherwise, would I really want
> the same thing, and no error, for ANY index larger than the length of the
> list?
>
> Rather, if there's a specific index we want, we want it to be there, and
> if not, then we are iterating over it, which handles any length (including
> zero) just fine.
>
> -CHB
>

dict.get is definitely much more useful. But list.get is still useful
reasonably often.

You can see quite a bit of demand for the method here:
https://stackoverflow.com/questions/5125619/why-doesnt-list-have-safe-get-method-like-dictionary

Below are some use cases I found and how they could be refactored with
.get. Apart from the first one, they were all found simply by grepping for
`except IndexError`. It's pretty easy to pick obvious use cases out from
there. In some cases readability suffers a bit and using .get might not be
the best idea, but I've included them anyway so that we can see what
over-eager usage of the method might look like.

```
_pytest/_code/source.py
if insert_index >= len(values):
    end = None
else:
    end = values[insert_index]

end = values.get(insert_index)

--------------------

prompt_toolkit/layout/layout.py
try:
    return self._stack[-2].content
except IndexError:
    return self._stack[-1].content

return self._stack.get(-2, self._stack[-1]).content

--------------------

prompt_toolkit/buffer.py
try:
    word = words[state.n]
except IndexError:
    word = ""

word = words.get(state.n, "")

--------------------

prompt_toolkit/widgets/menus.py
try:
    selected_item = self.selected_menu[level + 1]
except IndexError:
    selected_item = -1

selected_item = self.selected_menu.get(level + 1, -1)

--------------------

prompt_toolkit/document.py
try:
    return self.text[self.cursor_position + offset]
except IndexError:
    return ""

return self.text.get(self.cursor_position + offset, "")

--------------------

prompt_toolkit/contrib/regular_languages/lexer.py
try:
    return lines[lineno]
except IndexError:
    return []

return lines.get(lineno, [])

--------------------

pip/_internal/cli/autocompletion.py
try:
    subcommand_name = [w for w in cwords if w in subcommands][0]
except IndexError:
    subcommand_name = None

subcommand_name = [w for w in cwords if w in subcommands].get(0)

--------------------

pip/_internal/cli/autocompletion.py
try:
    current = cwords[cword - 1]
except IndexError:
    current = ''

current = cwords.get(cword - 1, '')

--------------------

pip/_internal/configuration.py
try:
    return self._get_parser_to_modify()[0]
except IndexError:
    return None

return self._get_parser_to_modify().get(0)

--------------------

pip/_vendor/distlib/resources.py
try:
    result = self.index[i].startswith(path)
except IndexError:
    result = False

result = self.index.get(i, "").startswith(path)

--------------------

stack_data/core.py
try:
    return not self.lines[i - 1].strip()
except IndexError:
    return False

return not self.lines.get(i - 1, "not blank").strip()

--------------------

parso/tree.py
try:
    return self.parent.children[i + 1]
except IndexError:
    return None

return self.parent.children.get(i + 1)

--------------------

ipython/IPython/core/completer.py
try:
    return self.matches[state]
except IndexError:
    return None

return self.matches.get(state)

--------------------

ipython/IPython/core/magics/basic.py
mode = ''
try:
    mode = parameter_s.split()[0][1:]
except IndexError:
    pass

mode = parameter_s.split().get(0, '')[1:]

--------------------

ipython/IPython/core/tests/simpleerr.py
try:
    mode = sys.argv[1]
except IndexError:
    mode = 'div'

mode = sys.argv.get(1, 'div')

--------------------

ipython/IPython/utils/text.py
try:
    tgt = parts[field]
    return tgt
except IndexError:
    return ""

return parts.get(field, "")

--------------------

py/_xmlgen.py
try:
    tag.parent = self.parents[-1]
except IndexError:
    tag.parent = None

tag.parent = self.parents.get(-1, None)

--------------------

ipython/IPython/core/tests/tclass.py
try:
    name = sys.argv[1]
except IndexError:
    pass
else:
    if name.startswith('C'):
        c = C(name)

name = sys.argv.get(1, "")
if name.startswith('C'):
    c = C(name)
 ```
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/7W74OCYU5WTYFNTKW7PHONUCD3U2S3OO/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to