Python ast.Compare() Examples

The following are 30 code examples of ast.Compare(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: setup_info.py    From pipenv with MIT License 6 votes vote down vote up
def unparse_IfExp(self, item):
        ops, truth_vals = [], []
        if isinstance(item.test, ast.Compare):
            left, ops, right = self.unparse(item.test)
        else:
            result = self.unparse(item.test)
            if isinstance(result, dict):
                k, v = result.popitem()
                if not v:
                    truth_vals = [False]
        for i, op in enumerate(ops):
            if i == 0:
                truth_vals.append(op(left, right[i]))
            else:
                truth_vals.append(op(right[i - 1], right[i]))
        if all(truth_vals):
            unparsed = self.unparse(item.body)
        else:
            unparsed = self.unparse(item.orelse)
        return unparsed 
Example #2
Source File: translation.py    From mochi with MIT License 6 votes vote down vote up
def translate_compare(self, exp):
        if len(exp) < 3:
            raise MochiSyntaxError(exp, self.filename)

        op_symbol = exp[0]
        op_name = op_symbol.name

        left, rights = exp[1], exp[2:]
        ops = [op_ast_map[op_name]] * len(rights)
        pre, left_value = self.translate(left, False)
        right_values = []
        for right in rights:
            right_pre, right_value = self.translate(right, False)
            pre = pre + right_pre
            right_values.append(right_value)

        return pre, ast.Compare(ops=ops,
                                left=left_value,
                                comparators=right_values,
                                lineno=op_symbol.lineno,
                                col_offset=0) 
Example #3
Source File: compiler.py    From Transcrypt with Apache License 2.0 6 votes vote down vote up
def visitSubExpr (self, node, child):
        def getPriority (exprNode):
            if type (exprNode) in (ast.BinOp, ast.BoolOp):
                return self.operators [type (exprNode.op)][1]
            elif type (exprNode) == ast.Compare:
                return self.operators [type (exprNode.ops [0])][1]  # All ops have same priority
            elif type (exprNode) == ast.Yield:
                return -1000000
            else:
                return 1000000  # No need for parenthesis

        if getPriority (child) <= getPriority (node):
            self.emit ('(')
            self.visit (child)
            self.emit (')')
        else:
            self.visit (child) 
Example #4
Source File: flatten.py    From kappa with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def visit_Compare(self, cmp: ast.Compare) -> VisitExprReturnT:
        result_actions = []
        left, left_actions = self.visit_expr(cmp.left)
        result_actions.extend(left_actions)

        comparators = []
        for comparator in cmp.comparators:
            comparator, comparator_actions = self.visit_expr(comparator)
            result_actions.extend(comparator_actions)
            comparators.append(comparator)

        cmp_flattened = ast.Compare(left=left, ops=cmp.ops, comparators=comparators)

        result_id = self.next_symbol_id()
        assign_node = assign(result_id, cmp_flattened)
        return load(result_id), result_actions + [assign_node] 
Example #5
Source File: SimulatorExpressionParser.py    From urh with GNU General Public License v3.0 6 votes vote down vote up
def validate_condition_node(self, node):
        if isinstance(node, ast.UnaryOp):
            if type(node.op) not in self.op_cond:
                self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)

            self.validate_condition_node(node.operand)
        elif isinstance(node, ast.Compare):
            if not (len(node.ops) == 1 and len(node.comparators) == 1):
                self.raise_syntax_error("", node.lineno, node.col_offset)

            if type(node.ops[0]) not in self.op_cond:
                self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)

            self.validate_compare_nodes(node.left, node.comparators[0])
        elif isinstance(node, ast.BoolOp):
            for node in node.values:
                self.validate_condition_node(node)
        else:
            self.raise_syntax_error("", node.lineno, node.col_offset) 
Example #6
Source File: compares.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def visit_Compare(self, node: ast.Compare) -> None:
        """
        Ensures that compares are written correctly.

        Raises:
            ConstantCompareViolation
            UselessCompareViolation
            UselessLenCompareViolation
            HeterogenousCompareViolation
            ReversedComplexCompareViolation

        """
        self._check_literal_compare(node)
        self._check_useless_compare(node)
        self._check_unpythonic_compare(node)
        self._check_heterogenous_operators(node)
        self._check_reversed_complex_compare(node)
        self.generic_visit(node) 
Example #7
Source File: magic_check_fn.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def visit_Compare(self, node):
    """Compare nodes occur for all sequences of comparison (`in`, gt, lt, etc.)
    operators. We only want to match `___ in instanceof(dict)` here, so we
    restrict this to Compare ops with a single operator which is `In` or
    `NotIn`.
    """
    node = self.generic_visit(node)

    if len(node.ops) == 1 and isinstance(node.ops[0], (ast.In, ast.NotIn)):
      cmps = node.comparators
      if len(cmps) == 1 and self._is_valid_resolved(cmps[0]):
        rslvd = cmps[0]
        if isinstance(rslvd.value, dict):
          node = ast.Compare(
            node.left,
            node.ops,
            [_resolved(rslvd.representation+".keys()",
                       sorted(rslvd.value.keys()),
                       valid=False)])

    return node 
Example #8
Source File: isolate_format.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify_ast(expr, variables_and_values):
  """Verifies that |expr| is of the form
  expr ::= expr ( "or" | "and" ) expr
         | identifier "==" ( string | int )
  Also collects the variable identifiers and string/int values in the dict
  |variables_and_values|, in the form {'var': set([val1, val2, ...]), ...}.
  """
  assert isinstance(expr, (ast.BoolOp, ast.Compare))
  if isinstance(expr, ast.BoolOp):
    assert isinstance(expr.op, (ast.And, ast.Or))
    for subexpr in expr.values:
      verify_ast(subexpr, variables_and_values)
  else:
    assert isinstance(expr.left.ctx, ast.Load)
    assert len(expr.ops) == 1
    assert isinstance(expr.ops[0], ast.Eq)
    var_values = variables_and_values.setdefault(expr.left.id, set())
    rhs = expr.comparators[0]
    assert isinstance(rhs, (ast.Str, ast.Num))
    var_values.add(rhs.n if isinstance(rhs, ast.Num) else rhs.s) 
Example #9
Source File: expr.py    From recruit with Apache License 2.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #10
Source File: SimulatorExpressionParser.py    From urh with GNU General Public License v3.0 6 votes vote down vote up
def evaluate_node(self, node):
        if isinstance(node, ast.BinOp):
            return self.operators[type(node.op)](self.evaluate_node(node.left),
                                                 self.evaluate_node(node.right))
        elif isinstance(node, ast.UnaryOp):
            return self.operators[type(node.op)](self.evaluate_node(node.operand))
        elif isinstance(node, ast.Compare):
            to_string = isinstance(node.comparators[0], ast.Str)

            return self.operators[type(node.ops[0])](self.evaluate_attribute_node(node.left, to_string),
                                                     self.evaluate_node(node.comparators[0]))
        elif isinstance(node, ast.BoolOp):
            func = all if isinstance(node.op, ast.And) else any
            return func(self.evaluate_node(value) for value in node.values)
        elif isinstance(node, ast.Str):
            return node.s
        elif isinstance(node, ast.Attribute):
            return self.evaluate_attribute_node(node)
        elif isinstance(node, ast.Num):
            return node.n
        else:
            logger.error("Error during parsing") 
Example #11
Source File: expr.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #12
Source File: expr.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #13
Source File: normalizer.py    From bigcode-tools with MIT License 6 votes vote down vote up
def normalize_compare(node):
    """Rewrites a compare expression to a `and` expression
    1 < 2 < 3 > 0
    1 < 2 and 2 < 3 and 3 > 0"""
    and_values = []
    left = node.left
    for (op, val) in zip(node.ops, node.comparators):
        comp = ast.Compare(ops=[op],
                           left=left,
                           comparators=[val],
                           lineno=node.lineno,
                           col_offset=node.col_offset)
        and_values.append(comp)
        left = val
    return ast.BoolOp(op=ast.And(),
                      values=and_values,
                      lineno=node.lineno,
                      col_offset=node.col_offset) 
Example #14
Source File: expr.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #15
Source File: stmt_visitor.py    From pyt with GNU General Public License v2.0 6 votes vote down vote up
def visit_While(self, node):
        label_visitor = LabelVisitor()
        test = node.test  # the test condition of the while loop
        label_visitor.visit(test)

        while_node = self.append_node(Node(
            'while ' + label_visitor.result + ':',
            node,
            path=self.filenames[-1]
        ))

        if isinstance(test, ast.Compare):
            # quirk. See https://greentreesnakes.readthedocs.io/en/latest/nodes.html#Compare
            self.process_loop_funcs(test.left, while_node)

            for comp in test.comparators:
                self.process_loop_funcs(comp, while_node)
        else:  # while foo():
            self.process_loop_funcs(test, while_node)

        return self.loop_node_skeleton(while_node, node) 
Example #16
Source File: pyupgrade.py    From pyupgrade with MIT License 6 votes vote down vote up
def _compare_to_3(
        test: ast.Compare,
        op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]],
    ) -> bool:
        if not (
                isinstance(test.ops[0], op) and
                isinstance(test.comparators[0], ast.Tuple) and
                len(test.comparators[0].elts) >= 1 and
                all(isinstance(n, ast.Num) for n in test.comparators[0].elts)
        ):
            return False

        # checked above but mypy needs help
        elts = cast('List[ast.Num]', test.comparators[0].elts)

        return elts[0].n == 3 and all(n.n == 0 for n in elts[1:]) 
Example #17
Source File: expression.py    From xcube with MIT License 6 votes vote down vote up
def transform_bool_op(self, op, values):
        name, precedence, assoc = _ExprTranspiler.get_op_info(op)

        if name == 'and' or name == 'or':
            expr = None
            for i in range(1, len(values)):
                expr = 'np.logical_%s(%s, {x%d})' % (name, '{x0}' if i == 1 else expr, i)
            return expr

        xes = []
        for i in range(len(values)):
            value = values[i]
            x = '{x%d}' % i
            other_op = getattr(value, 'op', None)
            if other_op:
                _, other_precedence, other_assoc = self.get_op_info(other_op)
                if i == 0 and other_precedence < precedence \
                        or i > 0 and other_precedence <= precedence:
                    x = '(%s)' % x
            xes.append(x)

        return (' %s ' % name).join(xes)

    # Compare(left, ops, comparators 
Example #18
Source File: expr.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #19
Source File: formatting.py    From snoop with MIT License 6 votes vote down vote up
def format_executing_node_exception(self, event):
        try:
            assert not NO_ASTTOKENS
            node = Source.executing(event.frame).node
            assert node
            
            description = {
                ast.Call: 'calling',
                ast.Subscript: 'subscripting',
                ast.Attribute: 'getting attribute',
                ast.Compare: 'comparing',
            }.get(type(node), 'evaluating')
            source = event.source.get_text_with_indentation(node)
            plain_prefix = u'!!! When {}: '.format(description)
            prefix = u'{c.red}{}{c.reset}'.format(plain_prefix, c=self.c)
            return indented_lines(
                prefix,
                source,
                plain_prefix=plain_prefix
            )
        except Exception:
            return [] 
Example #20
Source File: expr.py    From Computable with MIT License 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #21
Source File: setup_info.py    From requirementslib with MIT License 6 votes vote down vote up
def unparse_IfExp(self, item):
        ops, truth_vals = [], []
        if isinstance(item.test, ast.Compare):
            left, ops, right = self.unparse(item.test)
        else:
            result = self.unparse(item.test)
            if isinstance(result, dict):
                k, v = result.popitem()
                if not v:
                    truth_vals = [False]
        for i, op in enumerate(ops):
            if i == 0:
                truth_vals.append(op(left, right[i]))
            else:
                truth_vals.append(op(right[i - 1], right[i]))
        if all(truth_vals):
            unparsed = self.unparse(item.body)
        else:
            unparsed = self.unparse(item.orelse)
        return unparsed 
Example #22
Source File: parser.py    From vecpy with MIT License 5 votes vote down vote up
def expression(self, block, expr, var=None):
    if isinstance(expr, ast.Num):
      var = self.add_literal(expr.n)
    elif isinstance(expr, ast.Name):
      var = self.kernel.get_variable(expr.id)
      if var is None:
        raise Exception('Undefined Variable (%s)'%(expr.id))
      if var.is_fuse:
        raise Exception('Fuse variables are write-only')
      if var.is_arg:
        var.is_input = True
    elif isinstance(expr, ast.BinOp):
      var = self.binop(block, expr, var)
    elif isinstance(expr, ast.UnaryOp):
      var = self.unaryop(block, expr)
    elif isinstance(expr, ast.Call):
      var = self.call(block, expr, var)
    elif isinstance(expr, ast.Attribute):
      var = self.attribute(block, expr)
    elif isinstance(expr, ast.Compare):
      var = self.compare(block, expr)
    elif isinstance(expr, ast.BoolOp):
      var = self.boolop(block, expr)
    elif isinstance(expr, ast.Subscript):
      (var, assignment) = self.subscript(block, expr)
      block.add(assignment)
    else:
      Parser._dump(expr, 'Unexpected Expression')
      raise Exception('Unexpected Expression (%s)'%(expr.__class__))
    return var

  #Generates a new block mask 
Example #23
Source File: parser.py    From vecpy with MIT License 5 votes vote down vote up
def compare(self, block, cmp, var=None):
    if len(cmp.ops) > 1:
      #Chain multiple comparisons together (emulate a BoolOp)
      boolop = ast.BoolOp()
      boolop.op = ast.And()
      boolop.values = []
      left = cmp.left
      for op, comp in zip(cmp.ops, cmp.comparators):
        comparison = ast.Compare()
        comparison.left = left
        comparison.ops = [op]
        comparison.comparators = [comp]
        boolop.values.append(comparison)
        left = comp
      var = self.boolop(block, boolop, var)
    else:
      #Parse the left and right expressions
      left = self.expression(block, cmp.left)
      right = self.expression(block, cmp.comparators[0])
      #Parse the operator
      op = self.cmpop(cmp.ops[0])
      #Create a temporary variable to store the result of the comparison
      if var is None:
        var = self.add_variable(None, is_mask=True)
      comparison = ComparisonOperation(left, op, right)
      assignment = Assignment(var, comparison)
      block.add(assignment)
    return var

  #Parses a boolean operation (AST BoolOp) 
Example #24
Source File: test_main.py    From executing with MIT License 5 votes vote down vote up
def is_literal(node):
    if isinstance(node, ast.UnaryOp):
        return is_literal(node.operand)

    if isinstance(node, ast.BinOp):
        return is_literal(node.left) and is_literal(node.right)

    if isinstance(node, ast.Compare):
        return all(map(is_literal, [node.left] + node.comparators))

    if isinstance(node, ast.Subscript) and is_literal(node.value):
        if isinstance(node.slice, ast.Slice):
            return all(
                x is None or is_literal(x)
                for x in [
                    node.slice.lower,
                    node.slice.upper,
                    node.slice.step,
                ]
            )
        else:
            return is_literal(subscript_item(node))

    try:
        ast.literal_eval(node)
        return True
    except ValueError:
        return False 
Example #25
Source File: tests.py    From executing with MIT License 5 votes vote down vote up
def __lt__(self, other):
        node = self.get_node(ast.Compare)
        self.check(node.left, self)
        self.check(node.comparators[0], other)
        return self 
Example #26
Source File: parse.py    From mayo with MIT License 5 votes vote down vote up
def _eval(self, n):
        if isinstance(n, ast.Num):
            return n.n
        if isinstance(n, ast.Call):
            op = import_from_string(self._eval(n.func))
            args = (self._eval(a) for a in n.args)
            return op(*args)
        if isinstance(n, ast.Attribute):
            obj = self._eval(n.value)
            if isinstance(obj, str):
                return '{}.{}'.format(obj, n.attr)
            return getattr(obj, n.attr)
        if isinstance(n, ast.Name):
            return n.id
        if isinstance(n, ast.Str):
            return n.s
        if isinstance(n, ast.Compare):
            ops = n.ops
            rhs = n.comparators
            if len(ops) > 1 or len(rhs) > 1:
                raise NotImplementedError(
                    'We support only one comparator for now.')
            op = self._eval_expr_map[type(ops[0])]
            return op(self._eval(n.left), self._eval(rhs[0]))
        if isinstance(n, ast.IfExp):
            if self._eval(n.test):
                return self._eval(n.body)
            else:
                return self._eval(n.orelse)
        if isinstance(n, ast.NameConstant):
            return n.value
        if isinstance(n, ast.List):
            return [self._eval(e) for e in n.elts]
        if not isinstance(n, (ast.UnaryOp, ast.BinOp, ast.BoolOp)):
            raise TypeError('Unrecognized operator node {}'.format(n))
        op = self._eval_expr_map[type(n.op)]
        if isinstance(n, ast.UnaryOp):
            return op(self._eval(n.operand))
        if isinstance(n, ast.BoolOp):
            return op(*(self._eval(e) for e in n.values))
        return op(self._eval(n.left), self._eval(n.right)) 
Example #27
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_comparison_2(p):
    '''comparison : expr comparison_star'''
    #                  1               2
    ops, exprs = p[2]
    p[0] = ast.Compare(p[1], ops, exprs, rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(p[0], p[1]) 
Example #28
Source File: rewrite.py    From ward with MIT License 5 votes vote down vote up
def is_binary_comparison(node: ast.expr) -> bool:
    return isinstance(node.test, ast.Compare) and len(node.test.ops) == 1 
Example #29
Source File: utils.py    From executing with MIT License 5 votes vote down vote up
def __lt__(self, other):
        node = self.get_node(ast.Compare)
        self.check(node.left, self)
        self.check(node.comparators[0], other)
        return self 
Example #30
Source File: executing.py    From executing with MIT License 5 votes vote down vote up
def __init__(self, frame, stmts, tree):
        self.frame = frame
        self.tree = tree

        b = frame.f_code.co_code[frame.f_lasti]
        if not PY3:
            b = ord(b)
        op_name = dis.opname[b]

        if op_name.startswith('CALL_'):
            typ = ast.Call
        elif op_name == 'BINARY_SUBSCR':
            typ = ast.Subscript
        elif op_name.startswith('BINARY_'):
            typ = ast.BinOp
        elif op_name.startswith('UNARY_'):
            typ = ast.UnaryOp
        elif op_name in ('LOAD_ATTR', 'LOAD_METHOD', 'LOOKUP_METHOD'):
            typ = ast.Attribute
        elif op_name == 'COMPARE_OP':
            typ = ast.Compare
        else:
            raise RuntimeError(op_name)

        with lock:
            exprs = {
                node
                for stmt in stmts
                for node in ast.walk(stmt)
                if isinstance(node, typ)
                if not (hasattr(node, "ctx") and not isinstance(node.ctx, ast.Load))
            }

            self.result = only(list(self.matching_nodes(exprs)))