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

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

    Python's and and or syntaxes cannot directly be mapped to functions. These syntaxes are lazy evaluated: If the result of the left part of the expression allows to know the value of the whole expression, the right part is skipped. Since they introduce flow control, their behavior cannot be reproduced using an operator. To reduce confusion, python have chosen to simply not provide these methods.

    georg gives a good example of a situation where and laziness matters:

     if obj is not None and obj.is_valid():
         ...
    

    Now, if you don't need lazy evaluation, you can use abarnert's answer implementation:

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

    Usage:

    >>> or_(False, True)
    >>> and_(True, False)
    

    If you need lazy evaluation, you can use kindall's answer implementation:

    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)
    

    Note: As mentioned in the comments, the functions operator.and_ and operator.or_ correspond to the bitwise operators & and |. See: https://docs.python.org/3/library/operator.html#mapping-operators-to-functions

    Note that the names operators.and and operators.or aren't used: and and or are Python keywords so it would be a syntax error.

提交回复
热议问题