Why is operator module missing `and` and `or`?

后端 未结 4 1101
渐次进展
渐次进展 2021-01-22 05:04

operator module makes it easy to avoid unnecessary functions and lambdas in situations like this:

import operator

def mytest(op, list1, list2):
    ok = [op(i1,         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-22 05:17

    You can write these yourself, but you'll need to pass a function (e.g. lambda) for the second argument to prevent it from being evaluated at call time, assuming that the usual short-circuiting behavior is important to you.

    def func_or(val1, fval2):
        return val1 or fval2()
    
    def func_and(val1, fval2):
        return val1 and fval2()
    

    Usage:

    func_or(False, lambda: True)
    func_and(True, lambda: False)
    

提交回复
热议问题