Skip to content
Advertisement

Get __repr__ to return string that has same value when passed to eval?

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement