1

This might sound like a weird question and and most likely has no practical relevance but that said, I came around a (to me) strange behavior in python.

If I have a simple class that overrides the __gt__ method like this

class K:
    def __init__(self, names):
        if isinstance(names, list):
            self.names = names
        else:
            self.names = [names]

    def __gt__(self, other):
        assert isinstance(other, K)
        return K(self.names + other.names)

then I was thinking the following

 print((K("a") > K("b") > K("c")).names)

should result n

['a', 'b', 'c']

but instead I get

['b', 'c']

if I do

print(((K("a") > K("b")) > K("c")).names)

it works but without the additional brackets the first statement seems to have disappeared somehow. There is certainly something about the __gt__ method I do not quite understand correctly, can you pleas explain what I'm missing and why this is not working in the way I suspected.

man zet
  • 826
  • 9
  • 26
  • 6
    Chained comparisons have a special behavior in Python - it's what allows you to do things like `0 < X < 100`. Your expression is equivalent to `(K("a") > K("b")) and (K("b") > K("c"))` (except that the middle sub-expression doesn't actually get evaluated twice). – jasonharper May 12 '20 at 20:02
  • 3
    If you want some sort of concatenation behavior, I would recommend using `__rshift__` to override `>>` instead. – chepner May 12 '20 at 20:05
  • ok, yes thx to you all that answers my question! – man zet May 12 '20 at 20:05

0 Answers0