-1

I don't fully understand what is going on here. Why does the returned string from repr evaluate to False? If anyone can expand on what I'm not understanding here, that would be really appreciated.

class Bag(object):
    def __init__(self, iter_vals = []):
        self.iter_vals = iter_vals
        
    def __repr__(self):
        return f"Bag({str(self.iter_vals)})"
        
        
if __name__ == '__main__':
    b = Bag(['d','a','b','d','c','b','d'])
    print(eval(repr(b)) == b)

>>> False
  • Hmm, I’d guess because you need to implement `__eq__` on the class? – rv.kvetch Oct 24 '21 at 04:41
  • Unless you implement `eq` or this is some sort of @DataClass, equality on objects is defined as being the same object. – Frank Yellin Oct 24 '21 at 04:42
  • To clarify, since `__eq__` isn't implemented, Python falls back to using `id`, which you can see will not evaluate to `True` if you check `id(b)` and `id(eval(repr(b)))`. – ddejohn Oct 24 '21 at 04:44
  • Does this answer your question? [How is \_\_eq\_\_ handled in Python and in what order?](https://stackoverflow.com/questions/3588776/how-is-eq-handled-in-python-and-in-what-order) – ddejohn Oct 24 '21 at 04:45

1 Answers1

4

You also need to define an __eq__ method to define how a Bag is equal to another Bag:

class Bag(object):
    def __init__(self, iter_vals = []):
        self.iter_vals = iter_vals
        
    def __repr__(self):
        return f"Bag({str(self.iter_vals)})"

    def __eq__(self, other):
        if not isinstance(other,Bag):
            raise TypeError('not a Bag')
        return self.iter_vals == other.iter_vals
        
if __name__ == '__main__':
    b = Bag(['d','a','b','d','c','b','d'])
    print(eval(repr(b)) == b)  # True
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251