Python ast.BoolOp() Examples
The following are 30
code examples of ast.BoolOp().
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: parser.py From vecpy with MIT License | 6 votes |
def boolop(self, block, node, var=None): #Get the type of operation if isinstance(node.op, ast.And): op = Operator.bool_and elif isinstance(node.op, ast.Or): op = Operator.bool_or else: raise Exception('Unexpected BoolOp (%s)'%(node.op.__class__)) #Chain operations together left = self.expression(block, node.values[0]) for node_value in node.values[1:]: right = self.expression(block, node_value) operation = BinaryOperation(left, op, right) if node_value == node.values[-1] and var is not None: #The last operation in the chain should be assigned to this variable temp_var = var else: #Create a temporary variable to store the intermediate result temp_var = self.add_variable(None, is_mask=True) assignment = Assignment(temp_var, operation) block.add(assignment) left = temp_var return temp_var #Parses an array element (AST Subscript)
Example #2
Source File: tags_manager.py From golem with MIT License | 6 votes |
def _evaluate(self, expr): if isinstance(expr, ast.Expr): return self._evaluate(expr.value) elif isinstance(expr, ast.BoolOp): if isinstance(expr.op, ast.Or): evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values] return ' or '.join(evaluated) elif isinstance(expr.op, ast.And): evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values] return ' and '.join(evaluated) elif isinstance(expr, ast.UnaryOp): if isinstance(expr.op, ast.Not): return 'not {}'.format(self._evaluate(expr.operand)) elif isinstance(expr, ast.Num): return '"{}" in {}'.format(str(expr.n), self.tags) elif isinstance(expr, ast.Str): return '"{}" in {}'.format(expr.s, self.tags) elif isinstance(expr, ast.Name): return '"{}" in {}'.format(expr.id, self.tags) else: msg = ('unknown expression {}, the only valid operators for tag expressions ' 'are: \'and\', \'or\' & \'not\''.format(type(expr))) raise InvalidTagExpression(msg)
Example #3
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def visit_BoolOp(self, node): 'A custom BoolOp can be used in flattened AST' if type(node.op) not in (ast.Add, ast.Mult, ast.BitXor, ast.BitAnd, ast.BitOr): return self.generic_visit(node) # get constant parts of node: list_cste = [child for child in node.values if isinstance(child, ast.Num)] if len(list_cste) < 2: return self.generic_visit(node) rest_values = [n for n in node.values if n not in list_cste] fake_node = Unflattening().visit(ast.BoolOp(node.op, list_cste)) fake_node = ast.Expression(fake_node) ast.fix_missing_locations(fake_node) code = compile(fake_node, '<constant folding>', 'eval') obj_env = globals().copy() exec code in obj_env value = eval(code, obj_env) new_node = ast.Num(value) rest_values.append(new_node) return ast.BoolOp(node.op, rest_values)
Example #4
Source File: expr.py From recruit with Apache License 2.0 | 6 votes |
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 #5
Source File: conditions.py From wemake-python-styleguide with MIT License | 6 votes |
def _get_all_names( self, node: ast.BoolOp, ) -> List[str]: # We need to make sure that we do not visit # one chained `BoolOp` elements twice: self._same_nodes.append(node) names = [] for operand in node.values: if isinstance(operand, ast.BoolOp): names.extend(self._get_all_names(operand)) else: names.append( source.node_to_string( operators.unwrap_unary_node(operand), ), ) return names
Example #6
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, patt_ast, target_ast, rep_ast, nbits=0): 'Pattern ast should have as root: BinOp, BoolOp, UnaryOp or Call' if isinstance(patt_ast, ast.Module): self.patt_ast = patt_ast.body[0].value elif isinstance(patt_ast, ast.Expression): self.patt_ast = patt_ast.body else: self.patt_ast = patt_ast if isinstance(rep_ast, ast.Module): self.rep_ast = deepcopy(rep_ast.body[0].value) elif isinstance(rep_ast, ast.Expression): self.rep_ast = deepcopy(rep_ast.body) else: self.rep_ast = deepcopy(rep_ast) if not nbits: getsize = asttools.GetSize() getsize.visit(target_ast) if getsize.result: self.nbits = getsize.result # default bitsize is 8 else: self.nbits = 8 else: self.nbits = nbits
Example #7
Source File: test_asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_onBoolOp(self): 'Tests on BoolOp' expr_a = ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.Num(3)]) expr_b = ast.BoolOp(ast.Add(), [ast.Num(3), ast.Num(2), ast.Num(1)]) self.assertTrue(asttools.Comparator().visit(expr_a, expr_b)) expr_a = ast.BoolOp(ast.Add, [ast.Num(1), ast.BoolOp(ast.Mult(), [ast.Num(5), ast.Num(6)]), ast.Num(4)]) expr_b = ast.BoolOp(ast.Add, [ast.BoolOp(ast.Mult(), [ast.Num(6), ast.Num(5)]), ast.Num(4), ast.Num(1)]) self.assertTrue(asttools.Comparator().visit(expr_a, expr_b))
Example #8
Source File: conditions.py From wemake-python-styleguide with MIT License | 6 votes |
def _duplicated_isinstance_call(node: ast.BoolOp) -> List[str]: counter: DefaultDict[str, int] = defaultdict(int) for call in node.values: if not isinstance(call, ast.Call) or len(call.args) != 2: continue if not given_function_called(call, {'isinstance'}): continue isinstance_object = source.node_to_string(call.args[0]) counter[isinstance_object] += 1 return [ node_name for node_name, count in counter.items() if count > 1 ]
Example #9
Source File: test_flattening.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_afterSubMult(self): 'Tests after SubToMult pre-processing' tests = [("1 + 2 - 3", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.BinOp(ast.Num(-1), ast.Mult(), ast.Num(3))])), ("1 + 2 - 3 + 4", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.BinOp(ast.Num(-1), ast.Mult(), ast.Num(3)), ast.Num(4)])), ("(1 + 2) - (3 + 4)", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.BinOp(ast.Num(-1), ast.Mult(), ast.BinOp(ast.Num(3), ast.Add(), ast.Num(4)))]))] for teststring, ref_ast in tests: test_ast = ast.parse(teststring, mode="eval").body test_ast = pre_processing.all_preprocessings(test_ast) test_ast = Flattening(ast.Add).visit(test_ast) self.assertTrue(Comparator().visit(test_ast, ref_ast))
Example #10
Source File: transformers.py From mutatest with MIT License | 6 votes |
def visit_BoolOp(self, node: ast.BoolOp) -> ast.AST: """Boolean operations, AND/OR.""" self.generic_visit(node) log_header = f"visit_BoolOp: {self.src_file}:" node_span = NodeSpan(node) idx = LocIndex( ast_class="BoolOp", lineno=node_span.lineno, col_offset=node_span.col_offset, op_type=type(node.op), end_lineno=node_span.end_lineno, end_col_offset=node_span.end_col_offset, ) self.locs.add(idx) if idx == self.target_idx and self.mutation and not self.readonly: LOGGER.debug("%s mutating idx: %s with %s", log_header, self.target_idx, self.mutation) return ast.copy_location(ast.BoolOp(op=self.mutation(), values=node.values), node) LOGGER.debug("%s (%s, %s): no mutations applied.", log_header, node.lineno, node.col_offset) return node
Example #11
Source File: compiler.py From Transcrypt with Apache License 2.0 | 6 votes |
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 #12
Source File: translation.py From mochi with MIT License | 6 votes |
def translate_bool_op(self, exp): if not len(exp) >= 3: raise MochiSyntaxError(exp, self.filename) op_symbol = exp[0] op_name = op_symbol.name op = op_ast_map[op_name] pre = [] values = [] for value in exp[1:]: pre_value, value_value = self.translate(value, False) pre += pre_value values.append(value_value) return pre, ast.BoolOp(op=op, values=values, lineno=op_symbol.lineno, col_offset=0)
Example #13
Source File: SimulatorExpressionParser.py From urh with GNU General Public License v3.0 | 6 votes |
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 #14
Source File: SimulatorExpressionParser.py From urh with GNU General Public License v3.0 | 6 votes |
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 #15
Source File: normalizer.py From bigcode-tools with MIT License | 6 votes |
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 #16
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 #17
Source File: cheader.py From steamcontroller with MIT License | 6 votes |
def eval_expr(expr): """ Eval and expression inside a #define using a suppart of python grammar """ def _eval(node): if isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return OPERATORS[type(node.op)](_eval(node.left), _eval(node.right)) elif isinstance(node, ast.UnaryOp): return OPERATORS[type(node.op)](_eval(node.operand)) elif isinstance(node, ast.BoolOp): values = [_eval(x) for x in node.values] return OPERATORS[type(node.op)](**values) else: raise TypeError(node) return _eval(ast.parse(expr, mode='eval').body)
Example #18
Source File: _343.py From codetransformer with GNU General Public License v2.0 | 6 votes |
def normalize_boolop(expr): """ Normalize a boolop by folding together nested And/Or exprs. """ optype = expr.op newvalues = [] for subexpr in expr.values: if not isinstance(subexpr, ast.BoolOp): newvalues.append(subexpr) elif type(subexpr.op) != type(optype): newvalues.append(normalize_boolop(subexpr)) else: # Normalize subexpression, then inline its values into the # top-level subexpr. newvalues.extend(normalize_boolop(subexpr).values) return ast.BoolOp(op=optype, values=newvalues)
Example #19
Source File: expr.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
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 #20
Source File: expr.py From Splunking-Crime with GNU Affero General Public License v3.0 | 6 votes |
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: yacc.py From yaksok with BSD 3-Clause "New" or "Revised" License | 6 votes |
def p_logic_or_expr(t): '''logic_or_expr : logic_or_expr OR logic_and_expr | logic_and_expr''' if len(t) == 4: if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.Or): t[0] = t[1] t[0].values.append(t[3]) else: or_ast = ast.Or() or_ast.lineno = t.lineno(2) or_ast.col_offset = -1 # XXX t[0] = ast.BoolOp(or_ast, [t[1], t[3]]) t[0].lineno = t.lineno(2) t[0].col_offset = -1 # XXX else: t[0] = t[1]
Example #22
Source File: yacc.py From yaksok with BSD 3-Clause "New" or "Revised" License | 6 votes |
def p_logic_and_expr(t): '''logic_and_expr : logic_and_expr AND logic_expr | logic_expr''' if len(t) == 4: if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.And): t[0] = t[1] t[0].values.append(t[3]) else: and_ast = ast.And() and_ast.lineno = t.lineno(2) and_ast.col_offset = -1 # XXX t[0] = ast.BoolOp(and_ast, [t[1], t[3]]) t[0].lineno = t.lineno(2) t[0].col_offset = -1 # XXX else: t[0] = t[1]
Example #23
Source File: expr.py From Computable with MIT License | 6 votes |
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 #24
Source File: builder.py From staticfg with Apache License 2.0 | 6 votes |
def merge_exitcases(exit1, exit2): """ Merge the exitcases of two Links. Args: exit1: The exitcase of a Link object. exit2: Another exitcase to merge with exit1. Returns: The merged exitcases. """ if exit1: if exit2: return ast.BoolOp(ast.And(), values=[exit1, exit2]) return exit1 return exit2
Example #25
Source File: expr.py From elasticintel with GNU General Public License v3.0 | 6 votes |
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 #26
Source File: expr.py From vnpy_crypto with MIT License | 6 votes |
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 #27
Source File: parser.py From vecpy with MIT License | 5 votes |
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 #28
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_or_test_2(p): '''or_test : and_test or_test_star''' # 1 2 theor = ast.Or(rule=inspect.currentframe().f_code.co_name) inherit_lineno(theor, p[2][0]) p[0] = ast.BoolOp(theor, [p[1]] + p[2], rule=inspect.currentframe().f_code.co_name) inherit_lineno(p[0], p[1])
Example #29
Source File: preprocessors.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def wrap_cell_expression(source, template='{expr}'): """ If a cell ends in an expression that could be displaying a HoloViews object (as determined using the AST), wrap it with a given prefix and suffix string. If the cell doesn't end in an expression, return the source unchanged. """ cell_output_types = (ast.IfExp, ast.BoolOp, ast.BinOp, ast.Call, ast.Name, ast.Attribute) try: node = ast.parse(comment_out_magics(source)) except SyntaxError: return source filtered = source.splitlines() if node.body != []: last_expr = node.body[-1] if not isinstance(last_expr, ast.Expr): pass # Not an expression elif isinstance(last_expr.value, cell_output_types): # CAREFUL WITH UTF8! expr_end_slice = filtered[last_expr.lineno-1][:last_expr.col_offset] expr_start_slice = filtered[last_expr.lineno-1][last_expr.col_offset:] start = '\n'.join(filtered[:last_expr.lineno-1] + ([expr_end_slice] if expr_end_slice else [])) ending = '\n'.join(([expr_start_slice] if expr_start_slice else []) + filtered[last_expr.lineno:]) # BUG!! Adds newline for 'foo'; <expr> return start + '\n' + template.format(expr=ending) return source
Example #30
Source File: counts.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_conditions(self, node: ast.BoolOp) -> None: conditions_count = self._count_conditions(node) if conditions_count > constants.MAX_CONDITIONS: self.add_violation( complexity.TooManyConditionsViolation( node, text=str(conditions_count), baseline=constants.MAX_CONDITIONS, ), )