Python ast.Eq() Examples
The following are 30
code examples of ast.Eq().
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: test_transformers.py From mutatest with MIT License | 6 votes |
def test_MutateAST_visit_compare(idx, mut_op, lineno, compare_file, compare_expected_locs): """Test mutation of the == to != in the compare op.""" tree = Genome(compare_file).ast # apply the mutation to the original tree copy testing_tree = deepcopy(tree) mutated_tree = MutateAST(target_idx=compare_expected_locs[idx], mutation=mut_op).visit( testing_tree ) # revisit in read-only mode to gather the locations of the new nodes mast = MutateAST(readonly=True) mast.visit(mutated_tree) assert len(mast.locs) == 3 # check that the lineno marked for mutation is changed, otherwise original ops should # still be present without modification for loc in mast.locs: if loc.lineno == lineno and loc.col_offset == 11: assert loc.op_type == mut_op else: assert loc.op_type in {ast.Eq, ast.Is, ast.In} # based on compare_file fixture
Example #2
Source File: isolate_format.py From luci-py with Apache License 2.0 | 6 votes |
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 #3
Source File: parser.py From vecpy with MIT License | 6 votes |
def cmpop(self, op): if isinstance(op, ast.Eq): return Operator.eq elif isinstance(op, ast.NotEq): return Operator.ne elif isinstance(op, ast.Lt): return Operator.lt elif isinstance(op, ast.LtE): return Operator.le elif isinstance(op, ast.Gt): return Operator.gt elif isinstance(op, ast.GtE): return Operator.ge else: raise Exception('Unexpected CmpOp (%s)'%(op.__class__)) #Parses a function call (AST Call)
Example #4
Source File: python2ir.py From ppci with BSD 2-Clause "Simplified" License | 6 votes |
def gen_compare(self, condition, yes_block, no_block): # print(dir(c), c.ops, c.comparators) # TODO: chained operators! ( 'a < b < c < d' ) assert len(condition.ops) == len(condition.comparators) assert len(condition.ops) == 1 op_map = { ast.Gt: ">", ast.GtE: ">=", ast.Lt: "<", ast.LtE: "<=", ast.Eq: "==", ast.NotEq: "!=", } a = self.gen_expr(condition.left) op = op_map[type(condition.ops[0])] b = self.gen_expr(condition.comparators[0]) if a.ty is not b.ty: self.error(condition, "Type mismatch, types must be the same.") self.emit(ir.CJump(a, op, b, yes_block, no_block))
Example #5
Source File: rewrite.py From ward with MIT License | 6 votes |
def visit_Assert(self, node): if is_binary_comparison(node): if is_comparison_type(node, ast.Eq): return make_call_node(node, assert_equal.__name__) elif is_comparison_type(node, ast.NotEq): return make_call_node(node, assert_not_equal.__name__) elif is_comparison_type(node, ast.In): return make_call_node(node, assert_in.__name__) elif is_comparison_type(node, ast.NotIn): return make_call_node(node, assert_not_in.__name__) elif is_comparison_type(node, ast.Is): return make_call_node(node, assert_is.__name__) elif is_comparison_type(node, ast.IsNot): return make_call_node(node, assert_is_not.__name__) elif is_comparison_type(node, ast.Lt): return make_call_node(node, assert_less_than.__name__) elif is_comparison_type(node, ast.LtE): return make_call_node(node, assert_less_than_equal_to.__name__) elif is_comparison_type(node, ast.Gt): return make_call_node(node, assert_greater_than.__name__) elif is_comparison_type(node, ast.GtE): return make_call_node(node, assert_greater_than_equal_to.__name__) return node
Example #6
Source File: helper.py From YAPyPy with MIT License | 6 votes |
def comp_op_rewrite(op: t.Union[Tokenizer, t.List[Tokenizer]]): """ ('<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not') """ if isinstance(op, list): op = tuple(map(lambda it: it.value, op)) else: op = op.value return { '<': ast.Lt, '>': ast.Gt, '==': ast.Eq, '>=': ast.GtE, '<=': ast.LtE, '<>': lambda: raise_exp(NotImplemented), '!=': ast.NotEq, 'in': ast.In, ('is', ): ast.Is, ('is', 'not'): ast.IsNot, ('not', 'in'): ast.NotIn, }[op]()
Example #7
Source File: counts.py From wemake-python-styleguide with MIT License | 6 votes |
def _check_compares(self, node: ast.Compare) -> None: is_all_equals = all(isinstance(op, ast.Eq) for op in node.ops) is_all_notequals = all(isinstance(op, ast.NotEq) for op in node.ops) can_be_longer = is_all_notequals or is_all_equals threshold = constants.MAX_COMPARES if can_be_longer: threshold += 1 if len(node.ops) > threshold: self.add_violation( complexity.TooLongCompareViolation( node, text=str(len(node.ops)), baseline=threshold, ), )
Example #8
Source File: _analyze.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_Compare(self, node): node.obj = bool() for n in [node.left] + node.comparators: self.visit(n) op, arg = node.ops[0], node.comparators[0] # # node.expr.target = self.getObj(arg) # # arg.target = self.getObj(node.expr) # detect specialized case for the test if isinstance(op, ast.Eq) and isinstance(node.left, ast.Name): # check wether it can be a case val = arg.obj if isinstance(val, bool): val = int(val) # cast bool to int first if isinstance(val, (EnumItemType, int)): node.case = (node.left, val) # check whether it can be part of an edge check n = node.left.id if n in self.tree.sigdict: sig = self.tree.sigdict[n] v = self.getValue(arg) if v is not None: if v == 0: node.edge = sig.negedge elif v == 1: node.edge = sig.posedge
Example #9
Source File: compares.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_constant(self, op: ast.cmpop, comparator: ast.expr) -> None: if not isinstance(op, (ast.Eq, ast.NotEq, ast.Is, ast.IsNot)): return real = get_assigned_expr(comparator) if not isinstance(real, (ast.List, ast.Dict, ast.Tuple)): return length = len(real.keys) if isinstance( real, ast.Dict, ) else len(real.elts) if not length: self.add_violation(FalsyConstantCompareViolation(comparator))
Example #10
Source File: compiler.py From Transcrypt with Apache License 2.0 | 5 votes |
def visit_Compare (self, node): if len (node.comparators) > 1: self.emit ('(') left = node.left for index, (op, right) in enumerate (zip (node.ops, node.comparators)): if index: self.emit (' && ') if type (op) in (ast.In, ast.NotIn) or (self.allowOperatorOverloading and type (op) in ( ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE )): self.emit ('{} ('.format (self.filterId ( # Non-overloaded '__in__' if type (op) == ast.In else '!__in__' if type (op) == ast.NotIn else # Overloaded '__eq__' if type (op) == ast.Eq else '__ne__' if type (op) == ast.NotEq else '__lt__' if type (op) == ast.Lt else '__le__' if type (op) == ast.LtE else '__gt__' if type (op) == ast.Gt else '__ge__' if type (op) == ast.GtE else 'Never here' ))) self.visitSubExpr (node, left) self.emit (', ') self.visitSubExpr (node, right) self.emit (')') else: self.visitSubExpr (node, left) self.emit (' {0} '.format (self.operators [type (op)][0])) self.visitSubExpr (node, right) left = right if len (node.comparators) > 1: self.emit(')')
Example #11
Source File: pytables.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op
Example #12
Source File: pytables.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def visit_Assign(self, node, **kwargs): cmpr = ast.Compare(ops=[ast.Eq()], left=node.targets[0], comparators=[node.value]) return self.visit(cmpr)
Example #13
Source File: test_rewrite.py From ward with MIT License | 5 votes |
def _( src=each("assert x == y", "assert x is y", "assert x < y", "assert x is not y"), node_type=each(ast.Eq, ast.Is, ast.Lt, ast.IsNot), ): assert_node = ast.parse(src).body[0] assert is_comparison_type(assert_node, node_type)
Example #14
Source File: definitions.py From vkbottle with MIT License | 5 votes |
def gt_operator(d: ast.Eq): return "=="
Example #15
Source File: conftest.py From mutatest with MIT License | 5 votes |
def compare_expected_locs(): """The compare expected locations based on the fixture""" # Py 3.7 if sys.version_info < (3, 8): return [ LocIndex(ast_class="Compare", lineno=2, col_offset=11, op_type=ast.Eq), LocIndex(ast_class="CompareIs", lineno=5, col_offset=11, op_type=ast.Is), LocIndex(ast_class="CompareIn", lineno=8, col_offset=11, op_type=ast.In), ] # Py 3.8 return [ LocIndex( ast_class="Compare", lineno=2, col_offset=11, op_type=ast.Eq, end_lineno=2, end_col_offset=17, ), LocIndex( ast_class="CompareIs", lineno=5, col_offset=11, op_type=ast.Is, end_lineno=5, end_col_offset=17, ), LocIndex( ast_class="CompareIn", lineno=8, col_offset=11, op_type=ast.In, end_lineno=8, end_col_offset=17, ), ] #################################################################################################### # TRANSFORMERS: IF FIXTURES ####################################################################################################
Example #16
Source File: pytables.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op
Example #17
Source File: pytables.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def visit_Assign(self, node, **kwargs): cmpr = ast.Compare(ops=[ast.Eq()], left=node.targets[0], comparators=[node.value]) return self.visit(cmpr)
Example #18
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_comp_op_3(p): '''comp_op : EQEQUAL''' # 1 p[0] = ast.Eq(rule=inspect.currentframe().f_code.co_name)
Example #19
Source File: py_converter.py From incubator-tvm with Apache License 2.0 | 5 votes |
def create_match_check(self, pattern: Pattern, data): """Given an ADT match pattern and a (Python) expression pointing to an ADT value, this generates a Python expression that checks if the ADT value matches the given pattern (returning True or False).""" # wildcard or var match everything if isinstance(pattern, (relay.PatternWildcard, relay.PatternVar)): return NameConstant(True) conds = [] if isinstance(pattern, relay.PatternConstructor): # constructor patterns check whether the constructors match # and also the matches of any nested patterns # equiv: (arg.tag == patern_constructor.tag) conds.append(ast.Compare(ast.Attribute(data, 'tag', Load()), [ast.Eq()], [ast.Num(pattern.constructor.tag)])) assert isinstance(pattern, (relay.PatternConstructor, relay.PatternTuple)) # now check for any nested patterns for i in range(len(pattern.patterns)): nested_pat = pattern.patterns[i] # can safely skip var or wildcard patterns: they will # never cause a check to fail if not isinstance(nested_pat, relay.PatternConstructor): continue # index into the value corresponding to the subpattern field_index = ast.Subscript(ast.Attribute(data, 'fields', Load()), ast.Index(Num(i)), Load()) conds.append(self.create_match_check(nested_pat, field_index)) # if we do not need to check nested pattern, just return the single check if len(conds) == 1: return conds[0] # otherwise AND together any nested checks return ast.BoolOp(ast.And(), conds)
Example #20
Source File: _recompute.py From icontract with MIT License | 5 votes |
def visit_Compare(self, node: ast.Compare) -> Any: """Recursively visit the comparators and apply the operations on them.""" # pylint: disable=too-many-branches left = self.visit(node=node.left) comparators = [self.visit(node=comparator) for comparator in node.comparators] result = None # type: Optional[Any] for comparator, op in zip(comparators, node.ops): if isinstance(op, ast.Eq): comparison = left == comparator elif isinstance(op, ast.NotEq): comparison = left != comparator elif isinstance(op, ast.Lt): comparison = left < comparator elif isinstance(op, ast.LtE): comparison = left <= comparator elif isinstance(op, ast.Gt): comparison = left > comparator elif isinstance(op, ast.GtE): comparison = left >= comparator elif isinstance(op, ast.Is): comparison = left is comparator elif isinstance(op, ast.IsNot): comparison = left is not comparator elif isinstance(op, ast.In): comparison = left in comparator elif isinstance(op, ast.NotIn): comparison = left not in comparator else: raise NotImplementedError("Unhandled op of {}: {}".format(node, op)) if result is None: result = comparison else: result = result and comparison left = comparator self.recomputed_values[node] = result return result
Example #21
Source File: pytables.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op
Example #22
Source File: pytables.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def visit_Assign(self, node, **kwargs): cmpr = ast.Compare(ops=[ast.Eq()], left=node.targets[0], comparators=[node.value]) return self.visit(cmpr)
Example #23
Source File: BehavioralRTLIRGenL2Pass.py From pymtl3 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__( s, component ): super().__init__( component ) s.loop_var_env = set() s.tmp_var_env = set() # opmap maps an ast operator to its RTLIR counterpart. s.opmap = { # Bool operators # Note: we do not support boolean operators because Python does # not allow overloading And and Or operators. Using them in # expressions might lead to inconsistent semantics. # ast.And : bir.And(), ast.Or : bir.Or(), # Unary operators # Note: ast.Not is disallowed because it is a boolean operator # ast.Not : bir.Not(), ast.Invert : bir.Invert(), ast.UAdd : bir.UAdd(), ast.USub : bir.USub(), # Binary operators ast.Add : bir.Add(), ast.Sub : bir.Sub(), ast.Mult : bir.Mult(), ast.Div : bir.Div(), ast.Mod : bir.Mod(), ast.Pow : bir.Pow(), ast.LShift : bir.ShiftLeft(), ast.RShift : bir.ShiftRightLogic(), ast.BitOr : bir.BitOr(), ast.BitAnd : bir.BitAnd(), ast.BitXor : bir.BitXor(), # Compare bir.bir.operators ast.Eq : bir.Eq(), ast.NotEq : bir.NotEq(), ast.Lt : bir.Lt(), ast.LtE : bir.LtE(), ast.Gt : bir.Gt(), ast.GtE : bir.GtE() } # Override
Example #24
Source File: pytables.py From Computable with MIT License | 5 votes |
def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op
Example #25
Source File: pytables.py From Computable with MIT License | 5 votes |
def visit_Assign(self, node, **kwargs): cmpr = ast.Compare(ops=[ast.Eq()], left=node.targets[0], comparators=[node.value]) return self.visit(cmpr)
Example #26
Source File: builder.py From staticfg with Apache License 2.0 | 5 votes |
def invert(node): """ Invert the operation in an ast node object (get its negation). Args: node: An ast node object. Returns: An ast node object containing the inverse (negation) of the input node. """ inverse = {ast.Eq: ast.NotEq, ast.NotEq: ast.Eq, ast.Lt: ast.GtE, ast.LtE: ast.Gt, ast.Gt: ast.LtE, ast.GtE: ast.Lt, ast.Is: ast.IsNot, ast.IsNot: ast.Is, ast.In: ast.NotIn, ast.NotIn: ast.In} if type(node) == ast.Compare: op = type(node.ops[0]) inverse_node = ast.Compare(left=node.left, ops=[inverse[op]()], comparators=node.comparators) elif isinstance(node, ast.BinOp) and type(node.op) in inverse: op = type(node.op) inverse_node = ast.BinOp(node.left, inverse[op](), node.right) elif type(node) == ast.NameConstant and node.value in [True, False]: inverse_node = ast.NameConstant(value=not node.value) else: inverse_node = ast.UnaryOp(op=ast.Not(), operand=node) return inverse_node
Example #27
Source File: pyupgrade.py From pyupgrade with MIT License | 5 votes |
def _eq(test: ast.Compare, n: int) -> bool: return ( isinstance(test.ops[0], ast.Eq) and isinstance(test.comparators[0], ast.Num) and test.comparators[0].n == n )
Example #28
Source File: pytables.py From vnpy_crypto with MIT License | 5 votes |
def translate_In(self, op): return ast.Eq() if isinstance(op, ast.In) else op
Example #29
Source File: pytables.py From vnpy_crypto with MIT License | 5 votes |
def visit_Assign(self, node, **kwargs): cmpr = ast.Compare(ops=[ast.Eq()], left=node.targets[0], comparators=[node.value]) return self.visit(cmpr)
Example #30
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 5 votes |
def compare_ast_to_ir2(ast_node: ast.Compare, compilation_context: CompilationContext, in_match_pattern: bool, check_var_reference: Callable[[ast.Name], None], match_lambda_argument_names: Set[str], current_stmt_line: int): if len(ast_node.ops) != 1 or len(ast_node.comparators) != 1: raise CompilationError(compilation_context, ast_node, 'Comparison not supported.') # pragma: no cover if in_match_pattern: raise CompilationError(compilation_context, ast_node, 'Comparisons are not allowed in match patterns') lhs = ast_node.left op = ast_node.ops[0] rhs = ast_node.comparators[0] if isinstance(op, ast.Eq): return eq_ast_to_ir2(lhs, rhs, compilation_context, in_match_pattern, check_var_reference, current_stmt_line) elif isinstance(op, ast.NotEq): return not_eq_ast_to_ir2(lhs, rhs, compilation_context, in_match_pattern, check_var_reference, current_stmt_line) elif isinstance(op, ast.In): return in_ast_to_ir2(lhs, rhs, compilation_context, in_match_pattern, check_var_reference, current_stmt_line) elif isinstance(op, ast.Lt): return int_comparison_ast_to_ir2(lhs, rhs, '<', compilation_context, in_match_pattern, check_var_reference, current_stmt_line) elif isinstance(op, ast.LtE): return int_comparison_ast_to_ir2(lhs, rhs, '<=', compilation_context, in_match_pattern, check_var_reference, current_stmt_line) elif isinstance(op, ast.Gt): return int_comparison_ast_to_ir2(lhs, rhs, '>', compilation_context, in_match_pattern, check_var_reference, current_stmt_line) elif isinstance(op, ast.GtE): return int_comparison_ast_to_ir2(lhs, rhs, '>=', compilation_context, in_match_pattern, check_var_reference, current_stmt_line) else: raise CompilationError(compilation_context, ast_node, 'Comparison not supported.') # pragma: no cover