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

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

    Because you cannot convert boolean operators into python functions. Functions always evaluate their arguments, and boolean operators do not. Adding and and or to the operators module would also require adding a special kind of functions (like lisp "macros") that evaluate their arguments on demand. Obviously, this is not something python designers ever wanted. Consider:

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

    you cannot write this in a functional form. An attempt like

      if operator.xyz(obj is not None, obj.is_valid()) 
    

    will fail if obj is actually None.

提交回复
热议问题