How to tell mypy an object is always Falsy

Viewed 94

Consider this example, where we have a custom "implicit bool" class FalsyType.

import typing as t


class FalsyType:
    def __bool__(self) -> t.Literal[False]:
        return False


Falsy = FalsyType()

a: t.Union[FalsyType, str]
a = Falsy

mylist: t.List[str] = []
if a:
    mylist.append(a)

a = "Hello"
if a:
    mylist.append(a)

mypy (version=0.910 & python==3.8.8) gives the following error:

16:19: error: Argument 1 to "append" of "list" has incompatible type "FalsyType"; expected "str"  [arg-type]
        mylist.append(a)

How to make mypy understand that a is Falsy and cannot be added to mylist after the condition?

Using isinstance check you can work around this issue, however, this is easy to forget or misunderstand when you have various Falsy classes like this.

if not isinstance(a, FalsyType):
   mylist.append(a)

Related:

EDIT: Clarify that a can be a str

0 Answers
Related