Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Equivalent to Python Statement Logic

I'm trying to find the functional equivalent of logic statements in Python (e.g. and/or/not). I thought I had found them in the operator module, but the behavior is remarkable different.

For example, the and statement does the behavior I want, whereas operator.and_ seems to requir an explicit type comparison, or else it throws a TypeError exception.

>>> from operator import *
>>> class A: pass
... 
>>> and_(A(), True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'instance' and 'bool'
>>> A() and True
True

Is there something like the operator module, but containing functions that match the behavior of Python's statement logic exactly?

like image 615
Cerin Avatar asked Dec 06 '25 08:12

Cerin


1 Answers

The functions operator.and_ and operator.or_ are the equivalent of the bit-wise "and" function and "or" function, respectively. There are no functions representing the and and or operators in operator, but you can use the built-ins any() and all() instead. They will take a single sequence as argument, but you can simply pass a tuple of two entries to use them as binary operators.

Note that it is impossible to match the logic of and and or exactly with any function you call. For example

False and sys.stdout.write("Hello")

will never print anything, while

f(False, sys.stdout.write("Hello"))

will always print the output, regardless how f() is defined. This is also the reason they are omitted from operator.

like image 143
Sven Marnach Avatar answered Dec 07 '25 21:12

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!