There are two types of objects in Python. Mutable, and immutable.
Immutable
- State cannot be changed.
- Usually thought of as "primitive" types.
int, float, string, tuple, etc.
Mutable
- State can be updated and changed.
list, dict, set, bytearray, any object that is created via the class token.
Depending on the type that you are discussing when you say variable this will affect the operator ==. Immutable types will always be checked against the actual value (e.g. 1 == 1 is True), where mutable types are checked against the object's __eq__ method (which overloads the == sign).
All of the mutable types listed - except new objects initialized with class - have a built-in __eq__ methods that are used when the == sign is present. Assuming you are using your own object, take the following for example:
class Obj:
def __init__(self, integer):
self.integer = integer
print(Obj(1) == Obj(1)) # False
Notice that despite integer being equal for each Obj, due to the fact Obj is a mutable type without the __eq__ method Python will check if the objects are equal to each other based on their space in memory- in other words, for it to be True, the object must be the exact same one you initialized.
class Obj:
def __init__(self, integer):
self.integer = integer
obj = Obj(1)
print(obj == obj) # True
To manually overload the == sign, you must use the __eq__ method:
class Obj:
def __init__(self, integer):
self.integer = integer
def __eq__(self, other):
# Comparison of two integers.
return self.integer == other.integer
print(Obj(1) == Obj(1)) # True