0

I'm building a simple parser that should be able to read some logic and arithmetic, compile it into an AST, then evaluate it. In an effort to do so without using the evil eval, I came across this answer.

Then I realized, the builtin operator library has functions for almost everything, except the logical and and or, only the bitwise ones exist. Surprisingly, logical not also exists. Why is and and or missing? Why not but not and and or? And to follow the mentioned above answer, what function should I use for those two operators?

PS: I was checking for python3, but it looks like the same library in python2 has the same issue.

mewais
  • 1,265
  • 3
  • 25
  • 42
  • @hansolo But `not` is a keyword too. And yet it is an operator and has an equivalent function. – mewais Aug 02 '20 at 08:01

1 Answers1

0

You can implement logical equivalent of the bitwise operators by using operator.truth to convert the object to it's bool() value & then applying the bitwise operator:

from operator import truth, and_, or_


def logical_and(a, b):
    return and_(truth(a), truth(b))

def logical_or(a, b):
    return or_(truth(a), truth(b))

print(logical_and([], ''))
print(logical_or([], 'x'))

Result:

False
True
rdas
  • 20,604
  • 6
  • 33
  • 46
  • Sure, it is very easy to work around the whole thing. My question is about the underlying implementation of `and` and `or`. It's my understanding that the operator functions are how the actual operators eventually execute. So if `+` calls `operator.add` what does `and` do? – mewais Aug 02 '20 at 08:09
  • 1
    Actually it's t he other way around. `operator` functions are utility functions that just use the normal `&` & `|` operators. Those operators themselves are implemented by the Runtime (in C). You can check the source code here: https://github.com/python/cpython/blob/3.8/Lib/operator.py – rdas Aug 02 '20 at 08:11
  • By extension: `and` & `or` are also implemented in C - and (I guess) the authors decided not to include the equivalent in `operator` since the building blocks were already there & they would be easy to implement as I've done in my answer above – rdas Aug 02 '20 at 08:13