This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Better `TypeError` message when a string is indexed using a non int
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.9
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Rin, xtreak
Priority: normal Keywords:

Created on 2021-09-24 16:33 by Rin, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg402577 - (view) Author: Rin RIn (Rin) Date: 2021-09-24 16:33
The `TypeError` message when a string is indexed using a string should be similar to the `TypeError` message when a list or tuple is indexed using a string.

>>> my_str = 'Rin'
>>> my_str[1:3]  # works
'in'
>>> my_str['no']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

>>> my_str[slice(1, 3)]  # works with slices
'in'

Certainly it does work with slice as intended but the error message should explain that, as seen in the following

>>> my_list = [1, 2, 3]
>>> my_list['no']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str

>>> my_tuple = (1, 2, 3)
>>> my_tuple['no']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: tuple indices must be integers or slices, not str

The error message shows `slices` are indeed an option to use when indexing a list or tuple.

Would be happy to submit a documentation PR if this minor change would be accepted.
msg402578 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2021-09-24 17:28
See also https://bugs.python.org/issue44110 . This looks like a duplicate. Also https://bugs.python.org/issue35077
History
Date User Action Args
2022-04-11 14:59:50adminsetgithub: 89447
2021-09-24 17:28:19xtreaksetnosy: + xtreak
messages: + msg402578
2021-09-24 16:36:34Rinsettitle: Better `TypeError` message when a string is indexed using a string -> Better `TypeError` message when a string is indexed using a non int
2021-09-24 16:33:24Rincreate