Created
          January 25, 2013 15:13 
        
      - 
      
 - 
        
Save taldcroft/4635130 to your computer and use it in GitHub Desktop.  
    Expression evaluation
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
how can I use it?