Skip to content

Instantly share code, notes, and snippets.

@taldcroft
Created January 25, 2013 15:13
Show Gist options
  • Save taldcroft/4635130 to your computer and use it in GitHub Desktop.
Save taldcroft/4635130 to your computer and use it in GitHub Desktop.
Expression evaluation
import operator
class Query(object):
def __init__(self, name, val=None, left=None, right=None, op=None):
self.name = name
self.val = val
self.left = left
self.right = right
self.op = op
def __and__(self, other):
name = '({} and {})'.format(self.name, other.name)
return Query(name, left=self, right=other, op=operator.and_)
def __or__(self, other):
name = '({} or {})'.format(self.name, other.name)
return Query(name, left=self, right=other, op=operator.or_)
def __invert__(self):
name = '~{}'.format(self.name)
return Query(name, left=self, op=operator.not_)
def eval(self):
print('Eval({})'.format(self.name))
if self.op is not None:
left = self.left.eval()
if self.right is None:
print('{}({})'.format(self.op.__name__, left))
return self.op(left)
else:
right = self.right.eval()
print('{}({}, {})'.format(self.op.__name__, left, right))
return self.op(left, right)
else:
print('val={}'.format(self.val))
return self.val
@anetasie
Copy link

how can I use it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment