What are the operational methods for boolean 'and', 'or' in Python?

For example, they are defined in the operating module and can be used as such:

import operator
print operator.__add__   # alias add -> +
print operator.__sub__   # alias sub -> -
print operator.__and__   # alias and_ -> &
print operator.__or__    # alias or_ -> |

Then what is equivalent to andand or?

print operator."and ?????"  # should be boolean-and
print operator."or ????"    # should be boolean-or
+3
source share
3 answers

They do not exist. The best you can do is replace them with lambda:

band = (lambda x,y: x and y)
bor = (lambda x,y: x or y)

The reason is that you cannot implement full behavior andor or, because they can lock in.

eg:

if variable or long_fonction_to_execute():
    # do stuff

variable - True, long_fonction_to_execute , Python , or True . . , .

, :

:

if bor(variable, long_fonction_to_execute()):
    # do stuff

long_fonction_to_execute .

, - , , .

+6

and or , . - : .

+12

e-satis:

lazyand = (lambda x,y: x() and y())
lazyor = (lambda x,y: x() or y())

, , , thunks ( "() → value" ), . ( , y, ).

, "" and ( or) /.

andexpr = lazyand(lambda: false, lambda: never_executed())
andexpr() # false

, , thunks , . , operator. "".

.

+3

Source: https://habr.com/ru/post/1793994/


All Articles