What is the operator.methodcaller method in Python?
Overview
The operator module is a built-in module in Python. The module provides functions equivalent to the intrinsic operators of Python. For instance, we can use the operator.mul() method for multiplication instead of using the multiplication (*) operator.
The module’s functions come in handy when callable methods are given as arguments to another Python object.
The methodcaller() method
The methodcaller() method returns a callable object that calls the method name on its operand. It can call a method on an object by providing its name supplied as a string. Additional arguments and keyword arguments can also be passed on to the method.
Syntax
operator.methodcaller(name, /, *args, **kwargs)
Parameters
name: This is the method name.argsandkwargs: These are method arguments.
Return value
This method returns a callable object that calls the method name on its operand.
Example
from operator import methodcallerlst_pop = methodcaller('pop')lst = [1,2,3,4]popped_element = lst_pop(lst)print("%s.pop() = %s" % (lst, popped_element))element = 3lst_count = methodcaller('count', element)lst = [1, 2, 2, 3, 3, 3]count_of_element = lst_count(lst)print("%s.count(%s) = %s" % (lst, element, count_of_element))
Explanation
- Line 1: We import the
methodcallermethod from theoperatormodule. - Line 3: We obtain a callable for the
popfunction,lst_pop, of the list is obtained usingmethodcaller. Thepopmethod doesn’t take arguments. Hence, no arguments are given in the invocation of themethodcaller. - Line 4: We define a list of numbers called
lst. - Line 5: We invoke a
lst_popcallable withlstas the argument. The return value is the last element popped fromlst. - Line 6: We print the popped element along with
lst. - Line 8: We define an integer value called
element. - Line 9: We obtain a callable for the
countfunction calledlst_countof the list usingmethodcaller. Thecountmethod takes an argument, that is the element to count in the list. Hence,elementis given during the invocation of themethodcaller. - Line 10: We define a list of numbers with duplicates called
lst. - Line 11: We invoke a
lst_countcallable withlstas the argument. The return value is the number of occurrences ofelementinlst. - Line 12: We print the frequency of
elementalong withlst.