Is there a way to compare a Python class to None using the is
operator?
class DefaultValue:
def __init__(self, default, value=None):
self.default = default
self.value = value
def __str__(self):
return str(self.value or self.default)
def __eq__(self, other):
return self.value == other
def __hash__(self):
return hash(self.value)
d = DefaultValue(False)
str(d) # 'False'
d == None # True
d is None # False
Is there something I can implement on the class so that the is operator will return True when comparing to None?
You can't overload the is
operator because it is used to check if two variables refer to the same value, which you should never need to overload. The most similar thing is to overload ==
with the __eq__
method:
class MyClass:
def __eq__(self, other):
#code here