Python – Accessing Private Members During Same Class Comparison

object-orientedpython

I am writing a class which basically is a wrapper around a dictionary with some extra functionality. This dictionary is stored as protected member _store. Now I am writing a __eq__ method to compare objects of my class. The criterion is, if the underlying dictionaries are equal, the objects are equal, therefore the easiest approach would be:

def __eq__(self, other):
    return self._store == other._store

But this entails accessing the protected members of a third object. Although this third object belongs to the same class as self. Can we consider this breaking encapsulation??

The other option is to do an item comparison between the two objects, which leads to a slightly less efficient and longer code (keys set comparison and check that the key-value pairs of one object equal the ones of the other object).

Best Answer

Since you tagged this with , I'll give you the Python perspective on this.

In Python, this is entirely normal. Attributes are not private, they are merely marked as 'internal', by convention, by using a leading underscore. So _store is something that is 'internal' to the class, just as the implementation of __eq__ is an internal matter.

You are not breaking encapsulation here; you are merely providing a correct implementation of a hook method. Accessing other._store here is no different from accessing self._store in that respect. That's because Python is a pragmatic language, it is not a purist OO language (you can use functional and procedural paradigms whenever you feel that fits the problem space better, for example).

Note that you may want to return the NotImplemented singleton object for comparisons that your class doesn't support:

def __eq__(self, other):
    if not isinstance(other, MyClass):  # or not hasattr(other, '_store') perhaps
        return NotImplemented
    return self._store == other._store

Python would then delegate the test to the other object; if it doesn't implement the __eq__ method or returns NotImplemented as well, then Python falls back to an identity test (self is other).

You'll find this pattern (using internal attributes in comparison hook methods) throughout the Python standard library. For example, all comparison methods for the decimal.Decimal() class delegate to the Decimal._cmp() method, and the implementation for that method is based almost exclusively on using internal attributes and methods (_is_special, _isinfinity(), _sign, _exp and _int), accessed both on self and other.

Some more examples:

Related Topic