0

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?

atm
  • 1,684
  • 1
  • 22
  • 24

2 Answers2

2

https://docs.python.org/3/library/operator.html

Following similar syntax of the other operator overrides methods you have defined, you can do one for is_. Hope this helps!

Andrew Ray
  • 186
  • 1
  • 7
  • I don't think that is available to implement on the class itself, right? https://docs.python.org/3/reference/datamodel.html – atm Jan 04 '19 at 21:35
1

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
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42