Equality in Python
== (Same value)
== checks that two variables have the same value. The Python interpreter will look at the content of the variables to evaluate a == b.
For standard objects
a = [1, 2]
b = []
b.append(1)
b.append(2)
a == b
True
123456789 == 123456789
True
a = 123456789
b = 123456788+1
a == b
True
a = (1, 2, 3)
b = [1, 2, 3]
a == b
False
For custom objects
For custom objects, == has to specified via the magic method __eq__. Actually... for all objects!
class User:
def __init__(self, username: str, email: str):
self.username = username
self.email = email
User("francois", "francois@ens-lyon.fr") == User("francois", "francois@ens-lyon.fr")
False
class User:
def __init__(self, username: str, email: str):
self.username = username
self.email = email
def __eq__(self, other: object):
if isinstance(other, User):
return self.username == other.username and self.email == other.email
return NotImplemented
User("francois", "francois@ens-lyon.fr") == User("francois", "francois@ens-lyon.fr")
True
class User2:
def __init__(self, username: str, email: str):
self.username = username
self.email = email
User2("francois", "francois@ens-lyon.fr") == User2("francois", "francois@ens-lyon.fr")
False
is (Same object)
is means the same object. The Pyther interpreter will just check the memory address. a is b is true iff the memory address of a and b are the same (same pointers, i.e. pointers pointed to the very same object).
class Person:
pass
a = Person()
b = Person()
a is b
False
class Person:
pass
a = Person()
b = a
a is b
True
a = 123456789
b = 123456789
a is b
False
a = 123456789
b = a
a is b
True
a = 123456789
b = 123456788+1
a is b
False
a = 2
b= 1+1
a is b
True
a = [1,2]
b = a
a is b
True
a = (1, 2, 3)
b = (1, 2, 3)
a is b
False
Summary
In German:
isisdas selbe==isdas gleiche