[issue44110] Improve string's __getitem__ error message

Miguel Brito report at bugs.python.org
Tue May 11 16:50:25 EDT 2021


New submission from Miguel Brito <miguel.mdebrito at gmail.com>:

I noticed that __getitem__ message, although helpful, could be improved a bit further. This will also make it consistent with other error messages such as the ones raised by `str.count`, `str.split`, `str.endswith` and so many others.

Currently, the error message goes like this: "TypeError: string indices must be integers" but we could specify the type of the object passed as argument to __getitem__. So, for example:

```
>>> idx = '1'
>>> s = 'abcde'
>>> s[idx]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not 'str'
```

This makes easier to debug and it is also consistent with other methods:

>>> "alala".count(8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

>>> "lala|helo".split(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str or None, not int

>>> 1 in "lala"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int

>>> "lala|helo".split(object())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str or None, not object

----------
components: Interpreter Core
messages: 393473
nosy: miguendes
priority: normal
severity: normal
status: open
title: Improve string's __getitem__ error message
type: enhancement
versions: Python 3.10, Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44110>
_______________________________________


More information about the Python-bugs-list mailing list