Skip to content

[1.20 regression] Per-module strict_optional = True override produces spurious [index] errors #21261

@chadhpaine

Description

@chadhpaine

Bug Report

Starting with mypy 1.20.0, ordinary slice expressions (s[2:], s[:n], s[a:b]) produce spurious [index] errors when a module is checked under a per-module strict_optional = True override while the global toggle is set strict_optional = False. The same code and configuration passes cleanly under mypy 1.19.1. Tests with strict_optional = True set globally (currently the default value, no per-module override) also pass cleanly — the error is specific to the two-tier pattern.

To Reproduce

mypy.ini:
[mypy]
strict_optional = False
follow_imports = skip

[mypy-repro]
strict_optional = True
follow_imports = normal

---
repro.py:
def trim_prefix(s: str) -> str:
    return s[2:]

def trim_suffix(s: str) -> str:
    return s[:-3]

def trim_both(s: str) -> str:
    return s[2:8]

def drop_first(items: list[str]) -> list[str]:
    return items[1:]

def cap_length(items: list[str], n: int) -> list[str]:
    return items[:n]

---
$ mypy --config-file mypy.ini repro.py

Expected Behavior

No errors. These statements are all examples of legal python syntax.

Actual Behavior

repro.py:2: error: Invalid index type "slice[int, None, None]" for "str"; expected type "SupportsIndex | slice[SupportsIndex, SupportsIndex | None, SupportsIndex]" [index]
repro.py:5: error: Invalid index type "slice[None, int, None]" for "str"; expected type "SupportsIndex | slice[SupportsIndex, SupportsIndex | None, SupportsIndex]" [index]
repro.py:8: error: Invalid index type "slice[int, int, None]" for "str"; expected type "SupportsIndex | slice[SupportsIndex, SupportsIndex | None, SupportsIndex]" [index]
repro.py:11: error: Invalid index type "slice[int, None, None]" for "list[str]"; expected type "slice[SupportsIndex, SupportsIndex | None, SupportsIndex]" [index]
repro.py:14: error: Invalid index type "slice[None, int, None]" for "list[str]"; expected type "slice[SupportsIndex, SupportsIndex | None, SupportsIndex]" [index]
Found 5 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.20.0, 1.20.1 (regression); 1.19.1 (clean)
  • Mypy command-line flags: none beyond --config-file
  • Mypy configuration options: see mypy.ini above
  • Python version used: 3.14

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions