__eq__ override question

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
jlawson
Posts: 8
Joined: Sat Jun 07, 2014 7:12 pm

__eq__ override question

Post by jlawson » Wed Nov 18, 2015 8:19 pm

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

pfalcon
Posts: 1155
Joined: Fri Feb 28, 2014 2:05 pm

Re: __eq__ override question

Post by pfalcon » Wed Nov 18, 2015 9:10 pm

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.
Awesome MicroPython list
Pycopy - A better MicroPython https://github.com/pfalcon/micropython
MicroPython standard library for all ports and forks - https://github.com/pfalcon/micropython-lib
More up to date docs - http://pycopy.readthedocs.io/

jlawson
Posts: 8
Joined: Sat Jun 07, 2014 7:12 pm

Re: __eq__ override question

Post by jlawson » Thu Nov 19, 2015 4:06 pm

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

Post Reply