python-operator-overloading
Design or review Python arithmetic, reflected, in-place, unary, or ordering operators and NotImplemented dispatch.
Files6
View on GitHubSKILL.mdskills/python-operator-overloading/SKILL.md
GitHubPurpose
Guide Python developers to implement operator overloading correctly: when to
overload versus using a named method, how to complete the two-sided dispatch
contract (__add__ / __radd__, return NotImplemented vs raise TypeError),
and how to keep comparison and ordering semantically consistent.
Trigger / When to use
Use this skill when:
- A class defines any of
__add__,__sub__,__mul__,__truediv__,__floordiv__,__mod__, or__pow__ - A class defines
__iadd__,__imul__, or other in-place operators - A class defines
__neg__,__pos__, or__abs__ - A class defines
__lt__,__le__,__gt__, or__ge__ - Mixed-type arithmetic must interoperate with a foreign type (
Money * int) - A reviewer is checking whether an operator implementation handles unsupported types correctly
Do not use this skill when:
- The question is about
__eq__or__hash__definition → usepython-data-model-methods - The question is about mutable vs immutable class design → use
python-class-design - The question is about
@functools.total_orderingdecorator mechanics → consult verified Python documentation; the ordinary-decorator skill excludes class decorators - The operator is framework-specific (SQLAlchemy, NumPy broadcasting, etc.)
Inputs
- The class definition and the operator methods under review or authorship
- The types the operator is expected to accept (same-type, mixed-type, or unknown)
- Whether the class is mutable or immutable (relevant for in-place return contract)
- Whether the class must support reflected arithmetic (e.g.,
3 + obj) - Whether the class should be fully ordered (sort key, comparison operators)
Process
Decide whether to overload at all. Overload when the operation has clear mathematical or domain semantics (
Vector + Vector,Money * int). Use a named method (.add(),.scaled_by()) when the meaning is ambiguous.Return
NotImplementedfor unsupported types — never raiseTypeErrordirectly.TypeErrorkills the dispatch chain;NotImplementedlets Python try the reflected operator on the other operand. Seereferences/binary-operators.md§ NotImplemented Dispatch.Check reflected operator pairing. Every
__add__that may receive a foreign left-hand operand must be accompanied by__radd__. Without__radd__,3 + money_objraisesTypeErroreven when the operation is valid. Seereferences/binary-operators.md§ Reflected Operator Pairing.Apply the
isinstanceguard for mixed-type arithmetic. Guard withisinstance, handle the accepted type, and returnNotImplementedfor all others. Never rely on implicit coercion. Seereferences/binary-operators.md§ Mixed-Type Guard.Verify in-place operator return contract.
__iadd__and similar must returnself(mutable) or a new object (immutable). ReturningNone(implicit fall-through) silently rebinds the caller's variable toNone. Annotate with an explicit return type (e.g.,-> MyType) so pyright enforces this. Seereferences/in-place-and-unary-operators.md.Verify unary operator purity.
__neg__,__pos__, and__abs__must not mutateself; return a new object every time. Seereferences/in-place-and-unary-operators.md.Check ordering consistency with
__eq__. Verify the invariant:not (a < b) and not (b < a)must implya == b.__eq__is a pre-condition owned bypython-data-model-methods. Seereferences/comparison-and-ordering.md.Recommend
@functools.total_orderingwhen appropriate. If the class defines__eq__and exactly one ordering method, recommend@functools.total_orderingto complete the contract. For decorator mechanics, consult verified Python documentation;python-decoratorsexcludes class decorators.
Validation
Before proceeding, confirm:
- Operand types clear: are both left-hand and right-hand operand types known for the binary operator?
- Mutability intent defined: is the class mutable (
+=returnsself) or immutable (returns new object)? - Equality contract present: does
__eq__already exist or is it being designed together with ordering?
SOFT FAIL — ask and wait before continuing:
- Operand types are unknown → cannot determine if a reflected pair (
__radd__) is needed; ask before proceeding - Mutability intent is undecided → cannot determine in-place return semantics; ask before proceeding
BLOCKED — stop and redirect:
- Operator involves framework-specific semantics (SQLAlchemy
==, NumPy broadcasting) → out of scope; do not proceed - Task requires complex cross-type coercion (currency conversion, unit normalization) → delegate to adapter/service layer
- Task involves defining or reviewing
__eq__and__hash__together → stop and redirect topython-data-model-methods
Examples
class Money:
def __add__(self, other: object) -> "Money":
if not isinstance(other, Money):
return NotImplemented # lets Python try other.__radd__(self)
return Money(self.amount + other.amount, self.currency)
Negative — premature TypeError kills reflected dispatch:
class Money:
def __add__(self, other: object) -> "Money":
if not isinstance(other, Money):
raise TypeError(f"unsupported type: {type(other)}") # BAD
return Money(self.amount + other.amount, self.currency)
Outputs
- Operator methods that return
NotImplementedfor unsupported types - Reflected operator pairs (
__add__/__radd__) where mixed-type left-hand arithmetic is intended - In-place operator methods with explicit
return selforreturn new_obj - Unary operators that return new objects without mutating
self - Ordering operators semantically consistent with the class's
__eq__
Boundaries
python-data-model-methods— owns__eq__and__hash__. This skill treats__eq__as an external pre-condition for ordering consistency. Do not define or redefine__eq__using this skill.python-class-design— owns mutable vs immutable class design. This skill owns only the in-place operator return syntax contract; consultpython-class-designfor whether a class should be mutable at all.@functools.total_orderingmechanics — consult Python documentation; there is no class-decorator owner in this library. This skill recommends using it; class-decorator mechanics require verified Python documentation.- Framework-specific operators (SQLAlchemy
==expressions, NumPy broadcasting) are out of scope. - Complex cross-type coercion (currency conversion, unit normalization) is out of scope; delegate to an adapter or service layer.
- Inherited operator MRO resolution is out of scope; consult
python-class-design.
Failure Handling
- Insufficient context: if operand types or mutability intent cannot be determined, emit SOFT FAIL, state what is missing, and ask before recommending an operator form.
- Ambiguous requirement: if the class's equality contract is undefined, recommend defining
__eq__and__hash__first (usingpython-data-model-methods), then return to operator design. - Out-of-scope pattern detected: if the task involves framework-specific operators or cross-type coercion delegation, stop and redirect rather than producing a partial answer.
Local references
reference.md: navigation overview listing all three split reference files and their topic coveragereferences/binary-operators.md: R1, R2, R6, R7 — arithmetic operator families, reflected operator pairing,NotImplementeddispatch rules, and mixed-type arithmetic type-guardreferences/in-place-and-unary-operators.md: R3, R4 — in-place return contract (return selfvsreturn new_objvs forbiddenreturn None) and unary operator purity rulereferences/comparison-and-ordering.md: R5, R8 — ordering consistency rule,__eq__as pre-condition dependency, and@functools.total_orderingrecommendationexamples.md: 6 scenario sections covering all 8 requirements; required for this branching multi-path skill