reportUnnecessaryContains.md
April 8, 2026 · View on GitHub
Overview
reportUnnecessaryContains is a diagnostic in Pylance and Pyright that warns when a membership test (like in) is unnecessary or always evaluates to the same result due to type incompatibility or redundancy. This helps catch logic errors and keeps code clean and efficient.
Representative Issues
- #5218: Ensure that collection membership checks are performed with compatible types to avoid unnecessary diagnostics.
- #6087: Adjust
reportUnnecessaryContainsto correctly handle cases where values are equal but of different types. - #7354: Direct comparisons between objects of different types will always evaluate to False unless explicitly overridden.
Examples
Error:
def has_item(items: list[int], key: str) -> bool:
return key in items # str can never be contained in list[int]
Fix — use compatible types:
def has_item(items: list[int], key: int) -> bool:
return key in items
Or update the container type:
def has_item(items: list[int | str], key: str) -> bool:
return key in items
Common Fixes & Workarounds
- Ensure membership tests are performed between compatible types.
- Refactor code to remove redundant or logically impossible membership checks.
- Use explicit type conversions or assertions where needed for clarity and correctness.
- Review the Pyright configuration documentation for options to adjust or suppress this diagnostic if needed.
See Also
python.analysis.diagnosticSeverityOverrides— adjust or suppress this diagnosticpython.analysis.typeCheckingMode— controls which diagnostics are enabled by default