Skip to content

Compare Via Equals

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: compare-via-equals

Section titled “Sourcery refactoring id: compare-via-equals”

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

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

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 !=.