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”Description
Section titled “Description”Use == or != to compare str, bytes, int, and float.
Before
Section titled “Before”nr = 100if nr is calculate_sum(): do_x()nr = 100if nr == calculate_sum(): do_x()Before
Section titled “Before”if calculate_sum() is not 100: do_x()if calculate_sum() != 100: do_x()Explanation
Section titled “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 = 42other_nr = 42nr == other_nr=> Truenr is other_nr=> TrueFor huge numbers, the result is different:
nr = 42000other_nr = 42000nr == other_nr=> Truenr is other_nr=> FalseThe same applies for is not vs !=.