On Thu, Aug 27, 2020 at 3:09 PM M.-A. Lemburg <m...@egenix.com> wrote:

> I disagree on the above assessment. I have had such a get() builtin
> in mxTools for more than 20 years now and found that I hardly ever
> used it:
>
> https://www.egenix.com/products/python/mxBase/mxTools/doc/#_Toc293606201
>
> The reason is simple: unlike for dicts, where you often expect
> non-existing items (e.g. in keyword arguments, config files, etc.),
> having a missing index position in a list which you parse is
> almost always an error.
>
> Now, errors should be clearly marked and handled as such, hence
> having a try-except is the better coding strategy.
>
> For those cases, where a list can have a variable
> number of entries (e.g. optional arguments, file lists, etc.),
> code should clearly branch on list length and then determine the
> right strategy to fetch items.


I'm copying my earlier post because apparently linking to it repeatedly has
no effect and people keep on claiming that this method wouldn't be useful
while not saying a word about the evidence I presented that it would be.

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/PTJ2IGARXHP5UVHEBEX3YKDBLO2JDJT3/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to