Why does __ne__ exist?

Cody Piersall cody.piersall at gmail.com
Mon Jan 8 11:25:34 EST 2018


> Let's put it this way. Suppose that __eq__ existed and __ne__ didn't,
> just like with __contains__. Go ahead: sell the notion of __ne__.
> Pitch it, show why we absolutely need to allow this. Make sure you
> mention the potential confusion when subclassing. Be sure to show why
> it's okay for "not in" to force to boolean but "==" should allow any
> return value.

__ne__ and __eq__ are important for building mask arrays in NumPy,
which allow complex indexing operations.  A lot of NumPy's design was
inspired by MATLAB, so being able to index the same way as in MATLAB
is a pretty killer feature.

Indexing an array using mask arrays like this is idiomatic:

some_arr = np.array([-1, 0, 1, 2, 3, 4, 5, 2, -1, 3, -1, 6, 7, 3])
valid = some_arr[some_arr != -1]

Anybody with familiarity with NumPy appreciates that this is possible.

I imagine that ORMs like Django or SqlAlchemy also override __ne__ to
provide nice APIs.

Finally (and perhaps least imporant), there is a performance hit if
only allowing __eq__ and then taking its inverse.

Cody



More information about the Python-list mailing list