Opt-in error for if x:
when x: None | int
or None | str
etc.
#17892
Labels
if x:
when x: None | int
or None | str
etc.
#17892
Uh oh!
There was an error while loading. Please reload this page.
Feature
The
bug
function below has a bug: theelse
branch will execute both whenx
is None and when it is empty, and the latter is unexpected. The programmer was hoping""
would be handled by theif
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 likeNone | str
as expressing intent that""
should behave differently toNone
.This also applies to:
bool
,float
,int
,list
,dict
,set
(etc)__bool__
or__len__
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. WhenNone
is involved, this can lead to unexpected behaviour, where the falsey values like[]
,0
,""
,{}
are handled likeNone
.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 #17893, that I can complete with agreement/guidance.
The text was updated successfully, but these errors were encountered: