The Question Mark - blog by Mark Volkmann

Python operator module

The operator module in the Python standard library that provides that implement standard Python operators. These are useful for passing to higher-order functions. For example, .. TODO

The tables below show standard Python operators and their equivalent function from the operator module.

Relational

OperatorFunction
a < blt(a, b)
a <= ble(a, b)
a == beq(a, b)
a != bne(a, b)
a >= bge(a, b)
a > bgt(a, b)

Arithmetic

OperatorFunction
-aneg(a)
+apos(a)
a + badd(a, b)
a - bsub(a, b)
a * bmul(a, b)
a / btruediv(a, b)
a // bfloordiv(a, b)
a % bmod(a, b)
a ** bpow(a, b)

Bitwise

OperatorFunctionDescription
a & band_(a, b)bitwise and;
note trailing underscore in name
`ab`or_(a, b)
a ^ bxor(a, b)bitwise exclusive or
~ainv(a) or invert(a)bitwise inversion
a << blshift(a, b)left shift
a >> brshift(a, b)right shift

Indexing

OperatorFunctionDescription
obj[k]getitem(obj, k)indexed retrieval
obj[k] = vsetitem(obj, k, v)indexed assignment
del obj[k]delitem(obj, k)indexed deletion

Retrieval functions

OperatorFunctionDescription
obj.nameattrgetter(name)(obj)returns attribute value from object
attrgetter returns a function
n/aattrgetter(name1, name2, ...)(obj)returns tuple of attribute values from object
seq[i]itemgetter(i)(seq)returns i’th value from sequence
itemgetter returns a function
n/aitemgetter(i1, i2, ...)(obj)returns tuple of values from sequence
n/amethodcaller(name, args)(obj)calls a method with given arguments on an object

For example:

class Person:
    def __init__(self, name, hobby, height):
        self.name = name
        self.hobby = hobby
        self.height = height

    def __str__(self):
        return f'{self.name} likes {self.hobby} and is {self.height}" tall.'

    def grow(self, inches):
        self.height += inches

people = [
    Person('Mark', 'running', 74),
    Person('Tami', 'swimming', 65)
]

get_hobby = attrgetter('hobby') # works with objects, not dicts
hobbies = map(get_hobby, people)
print('hobbies =', list(hobbies)) # ['running', 'swimming']

get_data = attrgetter('hobby', 'height')
data = map(get_data, people)
print('data =', list(data)) # [('running', 74), ('swimming', 65)]

colors = ('red', 'orange', 'yellow', 'green', 'blue', 'purple')
pick_colors = itemgetter(1, 2, 4)
picked = pick_colors(colors)
print('picked =', picked) # ('orange', 'yellow', 'blue')

grow2 = methodcaller('grow', 2)
for person in people:
    grow2(person) # same as person.grow(2)
    print(person)
# Output:
# Mark likes running and is 76" tall.
# Tami likes swimming and is 67" tall.

Slicing

OperatorFunctionDescription
seq[i:j]getitem(seq, slice(i, j))slice retrieval
seq[i:j] = valuessetitem(seq, slice(i, j), values)slice assignment
del seq[i:j]delitem(seq, slice(i, j))slice deletion

Other

OperatorFunctionDescription
a + bconcat(a, b)returns new sequence created by concatenating two others
v in seqcontains(v, seq)determine if v is in seq
n/acountOf(a, b)returns number of occurrences of b in a;
note camelCase name
a is bis_(a, b)determines if a and b are the same object in memory;
note trailing underscore in name
a is not bis_not(a, b)determines if a and b are not the same object in memory
a @ bmatmul(a, b)matrix multiplication
s % objmod(s, obj)string formatting (SEEMS WRONG!)
v evaluated in
Boolean context
truth(v)returns the boolean value of v;
same as bool(v)
not vnot_(v)returns the negated boolean value of v;
note trailing underscore in name
n/alength_hint(seq)returns estimated number of elements, not length in bytes;
Why estimated?