Python Object-Oriented Python Dice Roller Giving a Hand

Prateek Sharan Lall
Prateek Sharan Lall
1,773 Points

TypeError: '<' not supported between instances of 'D6' and 'D6'

While running, I am getting this error. Please help, I cannot find what did I do wrong. Thanks.

from dice import D6

class Hand(list):
    def __init__(self, size=0, die_class=None, *args, **kwargs):
        if not die_class:
            raise ValueError("You must provide a die class")
        super().__init__()

        for _ in range(size):
            self.append(die_class())
        self.sort()


class YatzyHand(Hand):
    def __init__(self, *args, **kwargs):
        super().__init__(size=5, die_class=D6, *args, **kwargs)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 58,991 Points

The TypeError issue is being raised by the line self.sort() in Hand.__init__. The list.sort method needs a way to compare two items. The default method is to use the less than < operator. This requires the __lt__ method to be present in each object contained in the list. There are two choices:

Add comparisons __lt__, __gt__ method to the D6 class

    def __lt__(self, other):
        return int(self) < other

    def __gt__(self, other):
        return int(self) > other

    def __repr__(self):
        """Allow seeing value instead of object description"""
        return str(int(self))

Use key= parameter to the sort method:

    self.sort(key=lambda x: x.value)

Using the key argument says "Use this function, which returns the attribute item.value (an int), when comparing items ".

Post back if you need more help. Good luck!!

Steven Parker
Steven Parker
182,269 Points

Chris's suggestion will work, but in the video, a "__lt__" method is implemented in the "Die" class, which is the base (parent) class of D6. So it's not necessary to re-implement it in D6.

But check your "Die" implementation (in "dice.py", not shown here) in case that method was overlooked or has an error.

Chris Freeman
Chris Freeman
Treehouse Moderator 58,991 Points

Good points. The OP error message implied that __lt__ wasn't found in the local code, so I assumed it needed to be added in some class. I agree that Die is a better location to add this instead of D6.

Additionally, __lt__ may not be sufficient unless the other argument is handled directly.

If you get the message TypeError: '<' not supported between instances of 'int' and 'D6' (notice this is between int and D6 and not two D6 instances) then the __gt__ method is needed when the D6 is on the right-hand side of the less than comparison.