Page 1 of 1

__eq__ override question

Posted: Wed Nov 18, 2015 8:19 pm
by jlawson
Hi,
I'm working on a small module for MicroPython (and Python3) and have need to override several of the special methods like __add__ etc; which all work except for __eq__.
Under MicroPython __eq__ seems to only return a single boolean rather than the specified list as it does under Python3.

Using the following test case:

Code: Select all

class eqtest:

    def __init__(self, data):
        self.data = data

    def __eq__(self, other):
        return [self.data[i] == other.data[i] for i in range(len(self.data))]

x = eqtest([1,2,3])
y = eqtest([1,2,3])
z = eqtest([1,4,3])

print('x == y =>', x == y, '     x.__eq__(y) =>', x.__eq__(y))
print('x == z =>', x == z, '     x.__eq__(z) =>', x.__eq__(z))
Under Python3 the result is as expected (at least by me):

Code: Select all

$ python3 eq_test.py
x == y => [True, True, True]      x.__eq__(y) => [True, True, True]
x == z => [True, False, True]      x.__eq__(z) => [True, False, True]
but returns a single True or False under MicroPython unless invoked directly using x.__eq__(y).

Code: Select all

>>> import eq_test
x == y => False      x.__eq__(y) => [True, True, True]
x == z => False      x.__eq__(z) => [True, False, True]
https://docs.python.org/3/reference/dat ... ect.__eq__ talks about this but I don't see why it would not also work in MicroPython
I just wondered what the reasoning is if by design or if this is a bug (or just not implemented yet)?

Thanks,
Jamie

Re: __eq__ override question

Posted: Wed Nov 18, 2015 9:10 pm
by pfalcon
It talks about: "The correspondence between operator symbols and method names is as follows: ..., x==y calls x.__eq__(y)"

As result of "==" operator is bool, __eq__ also should return bool. CPython may try to handle what's arguably a programming error, but that's implementation detail of CPython. MicroPython doesn't do any tricks - they're expensive for performance. Just return a value of the expected type and you won't have any problems.

Re: __eq__ override question

Posted: Thu Nov 19, 2015 4:06 pm
by jlawson
Ok, thanks.
The module is a for 2-D matrix handling and I was trying to keep it compatible with Numpy as much as possible.
But I guess they diddle around with stuff.
Jamie