Skip to content

Compare Via Equals

Sourcery refactoring id: compare-via-equals

Description

Use == or != to compare str, bytes, int, and float.

Before

nr = 100
if nr is calculate_sum():
    do_x()

After

nr = 100
if nr == calculate_sum():
    do_x()

Before

if calculate_sum() is not 100:
    do_x()

After

if calculate_sum() != 100:
    do_x()

Explanation

While is compares whether two objects are the same, == compares whether their values are the same. For objects without an identity (aka value objects in domain-driven design), only the comparison of their values make sense. Prefer == to is both for the built-in value object types, but also for the value objects defined in your code.

Comparing the built-in number types via is can also lead to some surprising behaviour and bugs. For small numbers, is returns the same as ==:

nr = 42
other_nr = 42
nr == other_nr
=> True
nr is other_nr
=> True

For huge numbers, the result is different:

nr = 42000
other_nr = 42000
nr == other_nr
=> True
nr is other_nr
=> False

The same applies for is not vs !=.

Back to top