Rules of thumb for when to use operator overloading in python

operator-overloading, python

Solution

Operator overloading is mostly useful when you're making a new class that falls into an existing "Abstract Base Class" (ABC) -- indeed, many of the ABCs in standard library module collections rely on the presence of certain special methods (and special methods, one with names starting and ending with double underscores AKA "dunders", are exactly the way you perform operator overloading in Python). This provides good starting guidance.

For example, a `Container` class must override special method `__contains__`, i.e., the membership check operator `item in container` (as in, `if item in container:` -- don't confuse with the `for` statement, `for item in container:`, which relies on `__iter__`!-). Similarly, a `Hashable` must override `__hash__`, a `Sized` must override `__len__`, a `Sequence` or a `Mapping` must override `__getitem__`, and so forth. (Moreover, the ABCs can provide your class with mixin functionality -- e.g., both `Sequence` and `Mapping` can provide `__contains__` on the basis of your supplied `__getitem__` override, and thereby automatically make your class a `Container`).

Beyond the `collections`, you'll want to override special methods (i.e. provide for operator overloading) mostly if your new class "is a number". Other special cases exist, but resist the temptation of overloading operators "just for coolness", with no semantic connection to the "normal" meanings, as C++'s streams do for `<<` and `>>` and Python strings (in Python `2.*`, fortunately not in `3.*` any more;-) do for `%` -- when such operators do not any more mean "bit-shifting" or "division remainder", you're just engendering confusion. A language's standard library can get away with it (though it shouldn't;-), but unless your library gets as widespread as the language's standard one, the confusion will hurt!-)

Problem

From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading `+` you probably also want to overload `++` and `+=`, and also make sure to handle end cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application. Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me?

Original source

Related problems