3

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?

2
  • Why not roll your own? def and_(p1,p2): return p1 and p2 Commented Jan 22, 2011 at 21:33
  • 6
    @Bryan: Easy, yes - but OP is doing it right(tm) and asking for the existing wheel before reinventing it (even if it only takes a few seconds). Commented Jan 22, 2011 at 21:36

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.