Sub topic 9
Unary operators and abs()
This chapter assumes you can write a class with __init__ and __repr__. It also assumes you have seen how + maps to __add__ in the earlier chapters. Here you will implement the one-operand operators -x, +x and ~x, and the built-in abs(x).
The four hooks
A unary operator takes one operand. Python looks up the method on the operand's type and calls it with no arguments other than self.
| Syntax | Method | Typical meaning |
|---|---|---|
| `-x` | `__neg__` | Negation, the additive inverse |
| `+x` | `__pos__` | Identity, or a normalizing copy |
| `~x` | `__invert__` | Bitwise or logical inversion |
| `abs(x)` | `__abs__` | Magnitude or absolute value |
abs() is a built-in function, not an operator. It belongs in this chapter because it also takes one operand and dispatches to a dunder method on the type.
A first implementation
The Vector class from the earlier chapters already had __neg__ and __abs__. This version adds __pos__ and checks the results.
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __neg__(self):
return Vector(-self.x, -self.y)
def __pos__(self):
return Vector(+self.x, +self.y)
def __abs__(self):
return math.hypot(self.x, self.y)
v = Vector(3, 4)
print(-v) # Vector(-3, -4)
print(+v) # Vector(3, 4)
print(+v is v) # False
print(-(-v)) # Vector(3, 4)
print(abs(v)) # 5.0
print(abs(-v)) # 5.0Three points follow from this code.
- Each method builds and returns a new object. Nothing is modified in place.
__abs__returns afloat, not aVector. The magnitude of a vector is a scalar, so the return type differs from the operand's type. Python does not requireabs()to return the same type.math.hypotcomputes the length without the overflow and rounding problems ofmath.sqrt(x*x + y*y).
Never mutate self
Unary operators must not change the operand. People write -x expecting x to stay the same.
class BadVector:
def __init__(self, x, y):
self.x = x
self.y = y
def __neg__(self):
self.x, self.y = -self.x, -self.y # bug: changes the original
return self
b = BadVector(1, 2)
c = -b
print(b.x, c.x) # -1 -1 (b was changed, and c is the same object)After -b, the original b is changed and c is the same object. Code such as -b + b would give surprising results. Return a new object every time. Keep in-place changes for the __i*__ methods covered in the next chapter.
What +x is for
For numbers, +x does nothing. It exists for symmetry with -x. A class can give it a useful meaning, but the meaning should be a "clean-up" or "normalize" step that returns a new object. Two standard library examples show this.
collections.Counter defines +c to return a new counter with only the positive counts:
from collections import Counter
c = Counter(a=2, b=0, c=-1)
print(+c) # Counter({'a': 2})
print(-c) # Counter({'c': 1})decimal.Decimal defines +d to apply the current context's precision. The constructor does not round, so +d is the way to round a value to the context:
from decimal import Decimal, localcontext
d = Decimal('1.2345')
with localcontext() as ctx:
ctx.prec = 3
print(d) # 1.2345
print(+d) # 1.23If you have no sensible meaning for +x, a common choice is to return a copy, as Vector does above. You can also leave __pos__ undefined. Then +x raises TypeError, which is better than a meaning nobody expects.
Inversion with ~
~x calls __invert__. For integers it flips every bit. It suits classes that represent bit sets, flags or masks, where "the complement" is a natural idea.
class Bits:
def __init__(self, value, width=8):
self.width = width
self.value = value & ((1 << width) - 1)
def __repr__(self):
return f'Bits({self.value}, width={self.width})'
def __invert__(self):
return Bits(~self.value, self.width)
flags = Bits(5)
print(~flags) # Bits(250, width=8)
print(~~flags) # Bits(5, width=8)~self.value is a negative integer in Python, because integers have no fixed width. Masking with & ((1 << width) - 1) in __init__ brings it back into range. That is why the class stores a width. Do not use ~ for unrelated ideas, such as "transpose" or "reverse". Give those a named method.
Missing methods and NotImplemented
Unary operators have no reflected form, because there is no second operand to try. If the type lacks the method, Python raises TypeError immediately.
class Plain:
pass
for expression in (lambda: -Plain(), lambda: abs(Plain())):
try:
expression()
except TypeError as error:
print(error)
# bad operand type for unary -: 'Plain'
# bad operand type for abs(): 'Plain'Do not return NotImplemented from __neg__ or __abs__. That convention belongs to binary operators and comparisons. A unary method that cannot work for a given instance should raise an exception, for example ValueError, or you should not define it.
Precedence and chaining
Unary -, + and ~ bind tighter than * and /, but looser than **. So -x ** 2 means -(x ** 2):
print(-3 ** 2) # -9
print((-3) ** 2) # 9
print(- - 3) # 3This matters when your class also defines __pow__. The unary method runs on the result of the power, not on the base. Unary operators also chain from right to left, so -(+v) calls __pos__ first.
Keeping the methods consistent
Users expect certain relations to hold. Write a few assertions to check them:
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __neg__(self):
return Vector(-self.x, -self.y)
def __abs__(self):
return math.hypot(self.x, self.y)
v = Vector(3, 4)
assert -(-v) == v # negation is its own inverse
assert abs(-v) == abs(v) # magnitude ignores direction
assert abs(v) >= 0 # magnitude is never negative
print('all checks passed')Keep these points in mind:
- If
__neg__returns a different type than it receives,-(-x)may not round-trip. - Subclasses:
Vector(...)inside__neg__always builds a baseVector. Usetype(self)(...)if subclasses should keep their type. This only works if the subclass constructor takes the same arguments. - Floating point:
abs(v)returns a float, so compare it withmath.isclosein tests, not==.
Exercises
Exercise
A class defines __neg__ as self.value = -self.value; return self. What goes wrong in a = Temp(5); b = -a; print(a.value), and how do you fix it?
Show answer
It prints -5, because __neg__ changed a and returned the same object, so b is a. Unary operators should leave the operand unchanged. Fix it by returning a new instance: return Temp(-self.value).
Exercise
What happens when you call abs(obj) and the type of obj has no __abs__? Should __abs__ return NotImplemented in that situation?
Show answer
Python raises TypeError: bad operand type for abs(): '...'. __abs__ should not return NotImplemented. That convention applies to binary operators and comparisons, which have another operand to try. A unary method with no valid result should raise an exception, or the method should not be defined.
Exercise
Write a Money class holding an integer cents value, with __neg__, __abs__ and __repr__. Then say what type abs(Money(-250)) should return and why.
Show answer
class Money:
def _init(self, cents):
self.cents = cents
def repr(self):
return f'Money({self.cents})'
def neg(self):
return Money(-self.cents)
def abs_(self):
return Money(abs(self.cents))
It should return Money(250). The absolute value of an amount of money is still an amount of money, so returning the same type keeps further arithmetic and formatting working.