Python Operator Module
The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x + y.
Importing the Module
import operator
Arithmetic Operators
The module provides functions for standard arithmetic operations.
operator.add(a, b):a + boperator.sub(a, b):a - boperator.mul(a, b):a * boperator.truediv(a, b):a / boperator.floordiv(a, b):a // boperator.mod(a, b):a % boperator.pow(a, b):a ** b
import operator
a = 10
b = 3
print(operator.add(a, b)) # Output: 13
print(operator.floordiv(a, b)) # Output: 3
Comparison Operators
operator.lt(a, b):a < boperator.le(a, b):a <= boperator.eq(a, b):a == boperator.ne(a, b):a != boperator.ge(a, b):a >= boperator.gt(a, b):a > b
import operator
x = 5
y = 10
print(operator.lt(x, y)) # Output: True
Higher-Order Functions
The operator module provides tools for functional programming, often used with map(), sorted(), itertools.groupby(), etc.
itemgetter
Return a callable object that fetches item from its operand using the operandβs __getitem__() method.
import operator
data = [('apple', 3), ('banana', 2), ('pear', 5)]
# Sort by the second element (count)
data.sort(key=operator.itemgetter(1))
print(data)
# Output: [('banana', 2), ('apple', 3), ('pear', 5)]
attrgetter
Return a callable object that fetches attribute from its operand.
import operator
class User:
def __init__(self, name, id):
self.name = name
self.id = id
def __repr__(self):
return f"User({self.name})"
users = [User('Alice', 2), User('Bob', 1)]
# Sort by id
users.sort(key=operator.attrgetter('id'))
print(users)
# Output: [User(Bob), User(Alice)]
methodcaller
Return a callable object that calls the method name on its operand.
import operator
s = "hello world"
up = operator.methodcaller('upper')
print(up(s)) # Output: HELLO WORLD