user4813927
user4813927

Reputation:

Why use the functions in the operator module?

What is the point of python's operator module? There are many obviously redundant functions there and I don't understand why should one prefer to use these functions rather than other ways to do the same thing.

For example:

>>> import operator
>>> operator.truth(0)
False
>>> bool(0)
False

seem to do exactly the same thing.

Upvotes: 5

Views: 3378

Answers (3)

wim
wim

Reputation: 363253

Given the existence of bool, it's hard to think of any use-case for operator.truth these days. Note that bool was new in 2.2.1, and operator predates that, so it may only exist now for historical reasons. There are also other useless functions in the operator module, such as operator.abs, which simply calls the built-in abs.

Not everything in operator is entirely useless, though - operator's C implementation, if available, can offer performance gains over pure Python implementations. The itemgetter, attrgetter and methodcaller functions are more readable and generally better performing utility functions for tasks which are often handled by lambda functions.

Upvotes: 1

Mat
Mat

Reputation: 1403

Its sometimes useful to be able to access the functionality of an operator but as a function. For example to add two numbers together you could do.

>> print(1 + 2)
3

You could also do

>> import operator
>> print(operator.add(1, 2))
3

A use case for the function approach could be you need to write a calculator function which returns an answer given a simple formula.

import operator as _operator

operator_mapping = {
    '+': _operator.add,
    '-': _operator.sub,
    '*': _operator.mul,
    '/': _operator.truediv,
}

def calculate(formula):
    x, operator, y = formula.split(' ')

    # Convert x and y to floats so we can perform mathematical
    # operations on them.
    x, y = map(float, (x, y))

    return operator_mapping[operator](x, y)

print(calculate('1 + 2'))  # prints 3.0

Upvotes: 8

Martijn Pieters
Martijn Pieters

Reputation: 1124110

For completeness and consistency. Because having all operators in one place lets you do dynamic lookups later on:

getattr(operator, opname)(*arguments)

Omitting some operations because they are redundant would defeat that purpose. And because Python names are just references, it is cheap and easy to add a name to the operator module that is simply another reference.

Upvotes: 3

Related Questions