Opt-in error for `if x:` when `x: None | int` or `None | str` etc.
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
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 likebug(""))
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.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、issue の bug および fixed の例と併せて、pull request 17893 の未完了の実装を確認します。truthiness チェックで mypy が現在 None | str と None | int をどのように絞り込んでいるかを追跡し、続いてオプションの診断の動作と、built-ins、truthy 型、型変数の扱いを明らかにします。合意されたケースが、デフォルトでチェックを要求せずに診断されれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- 機能追加
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100