python / python/mypy

Opt-in error for `if x:` when `x: None | int` or `None | str` etc.

Open
#17,892 1 comment 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

The bug function below has a bug: the else branch will execute both when x is None and when it is empty, and the latter is unexpected. The programmer was hoping "" would be handled by the if branch.

It'd be handy if Mypy could (optionally) flag this sort of mistake, to help reminder the programmer that they probably should write something like fixed, i.e. take optional values like None | str as expressing intent that "" should behave differently to None.

def bug(x: None | str):
    if x: # error: None and str
        print(f"the str value is {x}") 
    else:
        print("the value is None")

def fixed(x: None | int):
    if x is not None: # no error
        print(f"the int value is {x}") 
    else:
        print("the value is None")

This also applies to:

  • built-ins like bool, float, int, list, dict, set (etc)
  • any "truthy" types, that implement __bool__ or __len__
  • arguably, type variables that could be substituted with any of those types (e.g. def bug[T](x: None | T) called like bug(""))

Pitch

It's very easy to write if x: out of habit when handling strings, lists and any other type with falsey values. When None is involved, this can lead to unexpected behaviour, where the falsey values like [], 0, "", {} are handled like None.

Mypy is very well positioned to catch this mistake given it has full type info (and indeed linters without full type info cannot do so).

This is likely to have some false-positives, and so should be optional. It feels conceptually similar, to me, to truthy-bool.

I've sketched an incomplete implementation in https://github.com/python/mypy/pull/17893, that I can complete with agreement/guidance.

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

Start by reviewing the incomplete implementation in pull request 17893 alongside the issue's bug and fixed examples. Trace how mypy currently narrows None | str and None | int in truthiness checks, then determine the optional diagnostic behavior and its handling of built-ins, truthy types, and type variables. Done means the agreed cases are diagnosed without requiring the check by default.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.