In what situation should the built-in 'operator' module be used in python?

前端 未结 6 2173
暖寄归人
暖寄归人 2020-12-23 19:44

I\'m speaking of this module: http://docs.python.org/library/operator.html

From the article:

The operator module exports a set of functions

6条回答
  •  生来不讨喜
    2020-12-23 20:18

    The module is useful when you need to pass a function as an argument to something. There are then two options: use the operator module, or define a new function (using def or lambda). If you define a function on the fly, this can create a problem if you need to pickle this function, either to save it to disk or to pass it between processes. While itemgetter is picklable, dynamically defined functions (either with def or lambda) are not. In the following example, replacing itemgetter with a lambda expression will result in a PicklingError.

    from operator import itemgetter
    
    def sort_by_key(sequence, key):
        return sorted(sequence, key=key)
    
    if __name__ == "__main__":
        from multiprocessing import Pool
    
        items = [([(1,2),(4,1)], itemgetter(1)),
                 ([(5,3),(2,7)], itemgetter(0))]
    
        with Pool(5) as p:
            result = p.starmap(sort_by_key, items)
        print(result)
    

提交回复
热议问题