Skip to content

invalid-index-type (RUF016) has false negatives and false positives #20204

@dscorbett

Description

@dscorbett

Summary

invalid-index-type (RUF016) has false negatives and false positives.

bool is a valid index type. RUF016 should allow it. Example:

$ cat >ruf016_1.py <<'# EOF'
print([1, 2, 3][False])
print([1, 2, 3][False:True:True])
# EOF

$ python ruf016_1.py
1
[1]

$ ruff --isolated check ruf016_1.py --select RUF016 --output-format concise -q
ruf016_1.py:1:17: RUF016 Indexed access to type `list` uses type `bool` instead of an integer or slice
ruf016_1.py:2:17: RUF016 Slice in indexed access to type `list` uses type `bool` instead of an integer
ruf016_1.py:2:23: RUF016 Slice in indexed access to type `list` uses type `bool` instead of an integer
ruf016_1.py:2:28: RUF016 Slice in indexed access to type `list` uses type `bool` instead of an integer

Lambda expressions, generator expressions, and t-strings are invalid. RUF016 should not allow them. Example:

$ cat >ruf016_2.py <<'# EOF'
try: [1, 2, 3][lambda: 0]
except TypeError as e: print(e)
try: [1, 2, 3][(x for x in ())]
except TypeError as e: print(e)
try: [1, 2, 3][t"x"]
except TypeError as e: print(e)
# EOF

$ python3.14 ruf016_2.py
ruf016_2.py:1: SyntaxWarning: list indices must be integers or slices, not function; perhaps you missed a comma?
  try: [1, 2, 3][lambda: 0]
ruf016_2.py:3: SyntaxWarning: list indices must be integers or slices, not generator; perhaps you missed a comma?
  try: [1, 2, 3][(x for x in ())]
ruf016_2.py:5: SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
  try: [1, 2, 3][t"x"]
list indices must be integers or slices, not function
list indices must be integers or slices, not generator
list indices must be integers or slices, not string.templatelib.Template

$ ruff --isolated check ruf016_2.py --select RUF016 --preview --target-version py314
All checks passed!

Version

ruff 0.12.11 (c2bc15b 2025-08-28)

Metadata

Metadata

Assignees

Labels

ruleImplementing or modifying a lint rule

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions