-
Notifications
You must be signed in to change notification settings - Fork 35
Open
Labels
Description
Maybe i missed something completely, but i could not figure out how to actually use the boolean expressions to boolean values to calculate the result, so i implemented something myself:
from operator import and_ as and_operator, or_ as or_operator
from boolean import BooleanAlgebra, AND, OR, NOT, Symbol
class Symbol_(Symbol):
def __call__(self, **kwargs):
return kwargs[self.obj]
class NOT_(NOT):
def __call__(self, **kwargs):
return not self.args[0](**kwargs)
class OR_(OR):
def __call__(self, **kwargs):
""" reduce is used as in e.g. OR(a, b, c, d) == OR(A, OR(b, OR(c, d)))"""
return reduce(or_operator, (a(**kwargs) for a in self.args))
class AND_(AND):
def __call__(self, **kwargs):
""" reduce is used as in e.g. AND(a, b, c, d) == AND(A, AND(b, AND(c, d)))"""
return reduce(and_operator, (a(**kwargs) for a in self.args))
class CallableBooleanAlgebra(BooleanAlgebra):
def __init__(self, *args, **kwargs):
super(CallableBooleanAlgebra, self).__init__(Symbol_class=Symbol_,
OR_class=OR_,
AND_class=AND_,
NOT_class=NOT_,
*args, **kwargs)
if __name__ == "__main__":
algebra = CallableBooleanAlgebra()
exp = algebra.parse("!(x|y&(x|!z))")
#call expression with keyword arguments matching the symbols:
assert exp(x=False, y=False, z=True) == True
I have written basic tests and checked whether the original tests pass (with some basic modifications) by replacing BooleanAlgebra with CallableBooleanAlgebra (import CallableBooleanAlgebra as BooleanAlgebra
).
Compliments for the tight implementation of boolean that made this relatively easy.
So my questions are:
- Is this functionality already there but did or completely miss it (making this a fun but somewhat useless exercise)?
- If not, is this something to add to the baseclasses (AND, OR, NOT, Symbol) themselves (but i can imagine this complicating subclassing a bit),
- Is there any interest in adding this to the repo in some other way?
Also comments, improvements, etc. are very welcome!
Cheers, Lars
JonGalarneau