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

后端 未结 4 1102
渐次进展
渐次进展 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:33

    The reason there's no operator.and is that and is a keyword, so that would be a SyntaxError.

    As tgh435 explained, the reason there's no renamed and function in operator is that it would be misleading: a function call always evaluates its operands, but the and operator doesn't. (It would also be an exception to an otherwise consistent and simple rule.)


    In your case, it looks like you don't actually care about short-circuiting at all, so can build your own version trivially:

    def and_(a, b):
        return a and b
    

    Or, if you're just using it once, even inline:

    mytest(lambda a, b: a and b, [-1, 2, -3], [1, -2, 33])
    

    In some cases, it's worth looking at all (and, for or, any). It is effectively short-circuited and expanded to arbitrary operands. Of course it has a different API than the operator functions, taking a single iterable of operands instead of two separate operands. And the way it short-circuits is different; it just stops iterating the iterable, which only helps if you've set things up so the iterable is only evaluating things as needed. So, it's usually not usable as a drop-in replacement—but it's sometimes usable if you refactor your code a bit.

提交回复
热议问题