python / python/mypy

Warn about non-optional conditions that don't provide __nonzero__?

Open
#8,284 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

needs discussion
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Maybe mypy should complain about Iterable[...] as an if condition, for example, since it generally doesn't define __nonzero__, so the check is likely unsafe? More generally, we could do this for all classes that don't define __nonzero__, but this could generate too many errors. One option would be to make this an optional check enabled by --strict, at least initially.

Examples:

def f(x: Iterable[int]) -> None:
    if not x:  # Might never be taken, or at least this could be inconsistently taken
        print('x')

class A:
    pass  # No __nonzero__

def g(a: A) -> None:
    if not a:   # Similar to above? What if there are subclasses of 'A'?
        print('x')

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no files, tests, or entry points. Start with the Iterable[int] and class A examples, then review how mypy currently handles conditions and strict-mode checks. Done would require a settled scope for the diagnostic, including subclass behavior and whether it is optional or enabled by --strict.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.