Seagan Damian
Seagan Damian

Reputation: 21

My __eq__() function is not returning the right values

I have the following code to build an array ADT but my __eq__() function is not working

class Array:

    def __init__(self, max_capacity):
        self.array = build_array(max_capacity)
        self.size = 0
        self.index = 0
        self.maxsize = max_capacity

    def __str__(self):
        string = "["
        for i in range(self.size):
            string += str(self.array[i])
            string += ', '
        string += ']'
        return string

    def __eq__(self, other):     
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        return False

if __name__ == "__main__":
    test_array = Array(6)

    test_array1 = Array(6)

    print(test_array.__eq__(test_array1))
    print(test_array)
    print(test_array1)

Right now, test_array.__eq__(test_array1) is returning False when it should be clearly True, I'm even printing everything out to make sure. I've no idea why it's returning False, any help is appreciated.

Here's the build_array function code

import ctypes


def build_array(size):
    if size <= 0:
        raise ValueError("Array size should be larger than 0.")
    if not isinstance(size,  int):
        raise ValueError("Array size should be an integer.")
    array = (size * ctypes.py_object)()
    array[:] = size * [None]
    return array

Upvotes: 0

Views: 284

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124100

You are asking Python to compare two ctypes arrays (all other key-value pairs are objects that do compare equal).

A ctypes array is only equal if it is referencing the same object

>>> a = build_array(6)
>>> b = build_array(6)
>>> a == b
False
>>> a == a
True

There is no support for testing if they have the same length and contain the same elements. You'll have to do so manually:

def __eq__(self, other):     
    if not isinstance(other, type(self)):
        return False
    if (self.index != other.index or self.size != other.size or
            self.maxsize != other.maxsize):
        return False
    return all(a == b for a, b in zip(self.array, other.array))

Upvotes: 2

Related Questions