Sub topic 9
Unary operators and abs()
This chapter assumes you can define a class with __init__ and __repr__, and that you know how Python maps + to __add__. Here you apply the same idea to operators that take one operand.
Which syntax maps to which method
A unary operator acts on a single object. Python looks the method up on the object's type and calls it with no arguments except self.
| Syntax | Method | Typical meaning |
|---|---|---|
| `-x` | `__neg__` | Negation |
| `+x` | `__pos__` | Identity, or a normalized copy |
| `~x` | `__invert__` | Bitwise inversion, or element-wise "not" |
| `abs(x)` | `__abs__` | Magnitude |
A worked example
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(abs(v)) # 5.0
print(+v is v) # FalseTwo choices in this code matter.
__neg__and__pos__return a newVector. They never changeself. A unary operator is an expression, so-vmust not alterv.__abs__returns a number, not aVector. Python does not check the return type, but callers expectabs()to give a magnitude.math.hypotcomputes the length without the overflow risk of a hand-written square root.
What `+x` is for
For many classes __pos__ just returns a copy or self. It is worth defining when + has a real meaning. decimal.Decimal uses it to round a value to the current context's precision. collections.Counter uses it to drop entries whose count is zero or negative. If your class has no such meaning, you can leave __pos__ out.
Missing methods and errors
If the type does not define the method, Python raises TypeError:
class Point:
pass
try:
-Point()
except TypeError as e:
print(e) # bad operand type for unary -: 'Point'Unlike binary operators, unary operators have no reflected form and no NotImplemented fallback. There is only one operand, so there is nothing else to try. If you cannot negate a particular instance, raise TypeError or ValueError yourself.
Common mistakes
- Mutating
selfin__neg__and returning it. After-v, the originalvhas changed. - Returning a
Vectorfrom__abs__. Code such asabs(a - b) < 0.01then fails with a comparison error. - Adding
__abs__without thinking about subclasses. Build the result withtype(self)(...)if subclasses may take different constructor arguments.
Exercise
A class defines __neg__ and __abs__ but not __pos__. What happens when you evaluate +obj, and what happens with abs(obj)?
Show answer
+obj raises TypeError: bad operand type for unary +, because Python finds no __pos__ on the type and has no fallback. abs(obj) calls __abs__ and returns whatever it returns, normally a non-negative number.