python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.55k stars 2.84k forks source link

Add support for type checking for the equality operator #12410

Closed louis-van-der-stam closed 2 years ago

louis-van-der-stam commented 2 years ago

Feature

def silly_sample1()-> bool:
    return 123 == 'something'  # Complain here about comparing different types of objects

def silly_sample2()-> bool:
    return 'Something'.lower == 'something'  # Complain here about comparing different types of objects

def silly_sample3()-> bool:
    return 'Something'.lower() == 'something'  # Works

Pitch

It would be really nice if these basic comparison operators would be capable of detecting these kinds of errors.

KotlinIsland commented 2 years ago

https://mypy-play.net/?mypy=latest&python=3.10&flags=strict&gist=a7b2df2dd3bd46aced211191762a8075

Mypy already performs these checks šŸ˜.

The annoying thing about mypy is that so many options are hidden and non-obvious. šŸ˜”

louis-van-der-stam commented 2 years ago

Thatā€™s really great! Is this under control of some configuration flag? For me this obviously does not happenā€¦.

KotlinIsland commented 2 years ago

Sure, strict = true, but more specifically it's strict_equality = true

https://mypy.readthedocs.io/en/stable/config_file.html#confval-strict_equality

louis-van-der-stam commented 2 years ago

Thanks didn't expect this to be disabled by default. Will check the other options also!

Thanks for pointing it out!

KotlinIsland commented 2 years ago

I would also recommend enabled_error_codes = "truthy-bool, redundant-expr"

KotlinIsland commented 2 years ago

@louis-van-der-stam There is a fork of mypy called basedmypy, where these options are all enabled by default.

JukkaL commented 2 years ago

Some of these strictness options aren't enabled by default because they can (or at least used to) generate false positives in some cases. Strict equality is mature enough now that we could consider enabling it by default.