Operators on Different Types

Operator overloading gives one spelling several meanings determined by the participating types and their agreed operations.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Read the operands first
  2. Design a meaningful example
  3. Work through an operation that looks familiar
  4. Make a custom operator predictable to its users

Read the operands first

In Python, [1] + [2] yields a new list with both items. Addition on integers yields their numeric sum. A user-defined class can provide special methods for suitable operators. Follow the types of the values to explain which rule applies before choosing an operator for an API.

Design a meaningful example

Adding two durations can reasonably produce an accumulated duration. Adding two calendar dates usually needs a domain-specific meaning that ordinary addition cannot convey. Test what happens with a supported pair and an unsuitable pair. Document result type and units in the function contract.[1][2]

Work through an operation that looks familiar

The operator + on two quantities can mean numerical addition, while the same spelling on two strings can mean concatenation. Try the pairs 2 and 5, then "2" and "5" in Python. They produce seven and the string "25" and both are successful expressions. A typed input boundary should establish which kind of value the next computation receives. A result of 25 in a total can be evidence that a reader retained the text fields.

Make a custom operator predictable to its users

For a type representing a distance, adding another value in a compatible unit can preserve distance. Adding an unlabeled text field or a temperature usually has no consistent meaning. Prefer the domain's natural operation and document how unsupported operands behave. For supported mixed units, test one exact converted result and a case crossing a precision limit. Values with units makes those conversions visible.

Check the direction of an operation when the runtime dispatches according to operand types. Reversing the order of subtraction changes the meaning even before considering type rules. An explicit named method can be clearer for specialized behavior that has no familiar interpretation under the operator.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩