[mypy] Boolean narrowing to literal is coming!

Allow booleans to be narrowed to literal types by ethan-leba · Pull Request #10389 · python/mypy · GitHub vient d’être mergée, je l’attendais :heart:

Avec un exemple c’est mieux :

from random import randint  # Pour bien bien perdre mypy :D
from typing import Union

str_or_bool: Union[str, bool]

if randint(0, 1):
    str_or_bool = "Hello"
else:
    str_or_bool = False

# là on est bien perdus, on ignore complètement si on a
# une chaîne ou un booléen dans `str_or_bool`...

if str_or_bool is True: # On élimine un cas ...
    print("OK")
elif str_or_bool is False: # On en élimine un autre ...
    print("KO")
elif str_or_bool:
    # OK donc si on arrive là c'est soit une chaîne soit un
    # booléen qui n'est ni True ni False ... donc c'est une chaîne !
    # Donc j'ai le droit de faire :
    print(">" + str_or_bool)
1 « J'aime »