why use the functions in the operator module?

  • Last Update :
  • Techknowledgy :

Here, we will look at some of the major operator functions we can use to perform mathematical operations such as addition, subtraction, division etc., on two input given values. Let's have a look at the following functions where we understand them in brief by using them in a program:,In this tutorial, we will learn about the operator module in Python and its various functions. We will use these functions of the operator module in a Python program to demonstrate their work.,We will look at some more functions from the operator module, but these functions belong to the relational operation category. With these functions, we can establish a relationship between any two given input numbers such as smaller one, larger one, equal etc. Look at the following operator functions from relational category with the use of each of them in a Python program:,Explanation: We performed the modulus operation on the user input numbers by giving them as arguments inside the mod() function and printed the modulus result.

Enter first integer number: 234
Enter second integer number: 729
Addition of input numbers given by you is: 963
Enter first integer number: 727
Enter second integer number: 344
Subtraction of input numbers given by you is: 383
Enter first integer number: 27
Enter second integer number: 23
Multiplication result of numbers given by you is: 621
Enter first integer number: 25
Enter second integer number: 6
True division result of numbers given by you is: 4.166666666666667
Enter first integer number: 25
Enter second integer number: 6
Floor division result of numbers given by you is: 4
Enter first integer number: 17
Enter second integer number: 13
Result of modulus operation on numbers given by you is: 4

Suggestion : 2

This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the 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. Many function names are those used for special methods, without the double underscores. For backward compatibility, many of these have a variant with the double underscores kept. The variants without the double underscores are preferred for clarity.,Many operations have an “in-place” version. Listed below are functions providing a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.,The operator module also defines tools for generalized attribute and item lookups. These are useful for making fast field extractors as arguments for map(), sorted(), itertools.groupby(), or other functions that expect a function argument.

def attrgetter( * items):
   if any(not isinstance(item, str) for item in items):
   raise TypeError('attribute name must be a string')
if len(items) == 1:
   attr = items[0]
def g(obj):
   return resolve_attr(obj, attr)
else:
   def g(obj):
   return tuple(resolve_attr(obj, attr) for attr in items)
return g

def resolve_attr(obj, attr):
   for name in attr.split("."):
   obj = getattr(obj, name)
return obj
def itemgetter( * items):
   if len(items) == 1:
   item = items[0]
def g(obj):
   return obj[item]
else:
   def g(obj):
   return tuple(obj[item]
      for item in items)
return g
>>> itemgetter(1)('ABCDEFG')
'B' >>>
itemgetter(1, 3, 5)('ABCDEFG')
   ('B', 'D', 'F') >>>
   itemgetter(slice(2, None))('ABCDEFG')
'CDEFG' >>>
soldier = dict(rank = 'captain', name = 'dotterbart') >>>
   itemgetter('rank')(soldier)
'captain'
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] >>>
   getcount = itemgetter(1) >>>
   list(map(getcount, inventory))[3, 2, 5, 1] >>>
   sorted(inventory, key = getcount)[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
def methodcaller(name, /, *args, **kwargs):
      def caller(obj):
      return getattr(obj, name)( * args, ** kwargs)
      return caller
>>> a = 'hello' >>>
   iadd(a, ' world')
'hello world' >>>
a
   'hello'

Suggestion : 3

Last Updated : 15 Jul, 2022

Output:

The addition of numbers is: 7
The difference of numbers is: 1
The product of numbers is: 12

Suggestion : 4

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

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

getattr(operator, opname)( * arguments)