Python ast.IfExp() Examples
The following are 26
code examples of ast.IfExp().
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: transformer.py From pyt with GNU General Public License v2.0 | 6 votes |
def visit_IfExp(self, node): if isinstance(node.test, (ast.Name, ast.Attribute)): return self.generic_visit(node) else: temp_var_id = '__if_exp_{}'.format(self._temporary_variable_index) self._temporary_variable_index += 1 assignment_of_test = ast.Assign( targets=[ast.Name(id=temp_var_id, ctx=ast.Store())], value=self.visit(node.test), ) ast.copy_location(assignment_of_test, node) self.assignments.append(assignment_of_test) transformed_if_exp = ast.IfExp( test=ast.Name(id=temp_var_id, ctx=ast.Load()), body=self.visit(node.body), orelse=self.visit(node.orelse), ) ast.copy_location(transformed_if_exp, node) return transformed_if_exp
Example #2
Source File: parser.py From myia with MIT License | 6 votes |
def process_IfExp(self, block: "Block", node: ast.IfExp) -> ANFNode: """Process if expression: `a if b else c`.""" cond = self.process_node(block, node.test) true_block, false_block = self.make_condition_blocks(block) true_block.graph.debug.location = self.make_location(node.body) false_block.graph.debug.location = self.make_location(node.orelse) tb = self.process_node(true_block, node.body, used=False) fb = self.process_node(false_block, node.orelse, used=False) tg = true_block.graph fg = false_block.graph tg.output = tb fg.output = fb switch = block.make_switch(cond, true_block, false_block) return block.apply(switch)
Example #3
Source File: checker.py From pyflakes with MIT License | 5 votes |
def handleNodeDelete(self, node): def on_conditional_branch(): """ Return `True` if node is part of a conditional body. """ current = getattr(node, '_pyflakes_parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current, '_pyflakes_parent', None) return False name = getNodeName(node) if not name: return if on_conditional_branch(): # We cannot predict if this conditional branch is going to # be executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name)
Example #4
Source File: py_converter.py From incubator-tvm with Apache License 2.0 | 5 votes |
def visit_if(self, if_block: Expr): cond_body, cond_defs = self.visit(if_block.cond) true_body, true_defs = self.visit(if_block.true_branch) false_body, false_defs = self.visit(if_block.false_branch) # need to get the value out of a NDArray to check the condition # equvialent to: val.asnumpy() cond_check = ast.Call(ast.Attribute(cond_body, 'asnumpy', Load()), [], []) ret = ast.IfExp(cond_check, true_body, false_body) return (ret, cond_defs + true_defs + false_defs)
Example #5
Source File: conditions.py From wemake-python-styleguide with MIT License | 5 votes |
def visit_IfExp(self, node: ast.IfExp) -> None: """ Checks ``if`` expressions. Raises: UselessLenCompareViolation NegatedConditionsViolation """ self._check_useless_len(node) self._check_negated_conditions(node) self.generic_visit(node)
Example #6
Source File: compares.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_nested_ifexpr(self, node: AnyIf) -> None: is_nested_in_if = bool( isinstance(node, ast.If) and list(walk.get_subnodes_by_type(node.test, ast.IfExp)), ) is_nested_poorly = walk.get_closest_parent( node, self._forbidden_expression_parents, ) if is_nested_in_if or is_nested_poorly: self.add_violation(NestedTernaryViolation(node))
Example #7
Source File: compares.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_simplifiable_ifexpr(self, node: ast.IfExp) -> None: conditions = set() if isinstance(node.body, ast.NameConstant): conditions.add(node.body.value) if isinstance(node.orelse, ast.NameConstant): conditions.add(node.orelse.value) if conditions == {True, False}: self.add_violation(SimplifiableIfViolation(node))
Example #8
Source File: token_generator.py From pasta with Apache License 2.0 | 5 votes |
def _scope_helper(node): """Get the closure of nodes that could begin a scope at this point. For instance, when encountering a `(` when parsing a BinOp node, this could indicate that the BinOp itself is parenthesized OR that the BinOp's left node could be parenthesized. E.g.: (a + b * c) or (a + b) * c or (a) + b * c ^ ^ ^ Arguments: node: (ast.AST) Node encountered when opening a scope. Returns: A closure of nodes which that scope might apply to. """ if isinstance(node, ast.Attribute): return (node,) + _scope_helper(node.value) if isinstance(node, ast.Subscript): return (node,) + _scope_helper(node.value) if isinstance(node, ast.Assign): return (node,) + _scope_helper(node.targets[0]) if isinstance(node, ast.AugAssign): return (node,) + _scope_helper(node.target) if isinstance(node, ast.Expr): return (node,) + _scope_helper(node.value) if isinstance(node, ast.Compare): return (node,) + _scope_helper(node.left) if isinstance(node, ast.BoolOp): return (node,) + _scope_helper(node.values[0]) if isinstance(node, ast.BinOp): return (node,) + _scope_helper(node.left) if isinstance(node, ast.Tuple) and node.elts: return (node,) + _scope_helper(node.elts[0]) if isinstance(node, ast.Call): return (node,) + _scope_helper(node.func) if isinstance(node, ast.GeneratorExp): return (node,) + _scope_helper(node.elt) if isinstance(node, ast.IfExp): return (node,) + _scope_helper(node.body) return (node,)
Example #9
Source File: checker.py From Transcrypt with Apache License 2.0 | 5 votes |
def handleNodeDelete(self, node): def on_conditional_branch(): """ Return `True` if node is part of a conditional body. """ current = getattr(node, 'parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current, 'parent', None) return False name = getNodeName(node) if not name: return if on_conditional_branch(): # We can not predict if this conditional branch is going to # be executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name)
Example #10
Source File: core.py From vulture with MIT License | 5 votes |
def _handle_conditional_node(self, node, name): if utils.condition_is_always_false(node.test): self._define( self.unreachable_code, name, node, last_node=node.body if isinstance(node, ast.IfExp) else node.body[-1], message="unsatisfiable '{name}' condition".format(**locals()), confidence=100, ) elif utils.condition_is_always_true(node.test): else_body = node.orelse if name == "ternary": self._define( self.unreachable_code, name, else_body, message="unreachable 'else' expression", confidence=100, ) elif else_body: self._define( self.unreachable_code, "else", else_body[0], last_node=else_body[-1], message="unreachable 'else' block", confidence=100, ) elif name == "if": # Redundant if-condition without else block. self._define( self.unreachable_code, name, node, message="redundant if-condition".format(**locals()), confidence=100, )
Example #11
Source File: test_ast.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_ifexp(self): l = ast.Name("x", ast.Load()) s = ast.Name("y", ast.Store()) for args in (s, l, l), (l, s, l), (l, l, s): self.expr(ast.IfExp(*args), "must have Load context")
Example #12
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 #13
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_test_2(p): '''test : or_test IF or_test ELSE test''' # 1 2 3 4 5 p[0] = ast.IfExp(p[3], p[1], p[5], rule=inspect.currentframe().f_code.co_name) inherit_lineno(p[0], p[1])
Example #14
Source File: parse.py From mayo with MIT License | 5 votes |
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 #15
Source File: checker.py From blackmamba with MIT License | 5 votes |
def handleNodeDelete(self, node): def on_conditional_branch(): """ Return `True` if node is part of a conditional body. """ current = getattr(node, 'parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current, 'parent', None) return False name = getNodeName(node) if not name: return if on_conditional_branch(): # We cannot predict if this conditional branch is going to # be executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name)
Example #16
Source File: checker.py From linter-pylama with MIT License | 5 votes |
def handleNodeDelete(self, node): def on_conditional_branch(): """ Return `True` if node is part of a conditional body. """ current = getattr(node, 'parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current, 'parent', None) return False name = getNodeName(node) if not name: return if on_conditional_branch(): # We cannot predict if this conditional branch is going to # be executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name)
Example #17
Source File: _recompute.py From icontract with MIT License | 5 votes |
def visit_IfExp(self, node: ast.IfExp) -> Any: """Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``.""" test = self.visit(node=node.test) if test: result = self.visit(node=node.body) else: result = self.visit(node=node.orelse) self.recomputed_values[node] = result return result
Example #18
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_ifexp(self): l = ast.Name("x", ast.Load()) s = ast.Name("y", ast.Store()) for args in (s, l, l), (l, s, l), (l, l, s): self.expr(ast.IfExp(*args), "must have Load context")
Example #19
Source File: expressions.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
def test_correct_comparing(self, node: Any = None) -> None: if not node: return if isinstance(node, Iterable): for item in node: self.test_correct_comparing(item) return if isinstance(node, ast.Expr): self.test_correct_comparing(node.value) return if isinstance(node, ast.BinOp): self.test_correct_comparing(node.left) self.test_correct_comparing(node.right) return if isinstance(node, ast.BoolOp): for val in node.values: self.test_correct_comparing(val) return if isinstance(node, ast.IfExp): self.test_correct_comparing(node.body) self.test_correct_comparing(node.test) self.test_correct_comparing(node.orelse) return if isinstance(node, ast.Compare): if isinstance(node.left, ast.Name): comparator = node.comparators[0] operation = node.ops[0] if isinstance(operation, ast.Is) or isinstance(operation, ast.IsNot): # Is or IsNot are allowed for NameConstant - None - only if isinstance(comparator, ast.NameConstant) and comparator.value is None: return node_text = self.stringify_node(node) self.warnings.append(f'Checking "{node_text}" ' 'is unsafe, use "==" operator instead') self.test_correct_comparing(comparator)
Example #20
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_ifexp(self): l = ast.Name("x", ast.Load()) s = ast.Name("y", ast.Store()) for args in (s, l, l), (l, s, l), (l, l, s): self.expr(ast.IfExp(*args), "must have Load context")
Example #21
Source File: rewrite.py From pytest with MIT License | 5 votes |
def visit_Name(self, name: ast.Name) -> Tuple[ast.Name, str]: # Display the repr of the name if it's a local variable or # _should_repr_global_name() thinks it's acceptable. locs = ast.Call(self.builtin("locals"), [], []) inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs]) dorepr = self.helper("_should_repr_global_name", name) test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) expr = ast.IfExp(test, self.display(name), ast.Str(name.id)) return name, self.explanation_param(expr)
Example #22
Source File: __init__.py From lambdascript with MIT License | 5 votes |
def __ast_check_tail_recursive__(node, symbol): # count all references of 'symbol' (even if not called) # count tail-calls of symbols n = sum((isinstance(w, ast.Name) and w.id==symbol) for w in ast.walk(node)) def count(no): if isinstance(no, ast.IfExp): return count(no.body) + count(no.orelse) if ( isinstance(no, ast.Call) and isinstance(no.func, ast.Name) and no.func.id == symbol ): return 1 return 0 return (n>0) and (n==count(node.body))
Example #23
Source File: rewrite.py From python-netsurv with MIT License | 5 votes |
def visit_Name(self, name): # Display the repr of the name if it's a local variable or # _should_repr_global_name() thinks it's acceptable. locs = ast.Call(self.builtin("locals"), [], []) inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs]) dorepr = self.helper("_should_repr_global_name", name) test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) expr = ast.IfExp(test, self.display(name), ast.Str(name.id)) return name, self.explanation_param(expr)
Example #24
Source File: rewrite.py From python-netsurv with MIT License | 5 votes |
def visit_Name(self, name): # Display the repr of the name if it's a local variable or # _should_repr_global_name() thinks it's acceptable. locs = ast.Call(self.builtin("locals"), [], []) inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs]) dorepr = self.helper("_should_repr_global_name", name) test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) expr = ast.IfExp(test, self.display(name), ast.Str(name.id)) return name, self.explanation_param(expr)
Example #25
Source File: expression.py From xcube with MIT License | 4 votes |
def _transpile(self, node: ast.AST) -> str: if isinstance(node, ast.Module): return self._transpile(node.body[0]) if isinstance(node, ast.Expr): return self._transpile(node.value) if isinstance(node, ast.Name): return self.transform_name(node) if isinstance(node, ast.NameConstant): return self.transform_name_constant(node) if isinstance(node, ast.Num): return self.transform_num(node) if isinstance(node, ast.Attribute): pat = self.transform_attribute(node.value, node.attr, node.ctx) x = self._transpile(node.value) return pat.format(x=x) if isinstance(node, ast.Call): pat = self.transform_call(node.func, node.args) xes = {'x%s' % i: self._transpile(node.args[i]) for i in range(len(node.args))} return pat.format(**xes) if isinstance(node, ast.UnaryOp): pat = self.transform_unary_op(node.op, node.operand) arg = self._transpile(node.operand) return pat.format(x=arg) if isinstance(node, ast.BinOp): pat = self.transform_bin_op(node.op, node.left, node.right) x = self._transpile(node.left) y = self._transpile(node.right) return pat.format(x=x, y=y) if isinstance(node, ast.IfExp): pat = self.transform_if_exp(node.test, node.body, node.orelse) x = self._transpile(node.test) y = self._transpile(node.body) z = self._transpile(node.orelse) return pat.format(x=x, y=y, z=z) if isinstance(node, ast.BoolOp): pat = self.transform_bool_op(node.op, node.values) xes = {'x%s' % i: self._transpile(node.values[i]) for i in range(len(node.values))} return pat.format(**xes) if isinstance(node, ast.Compare): pat = self.transform_compare(node.left, node.ops, node.comparators) xes = {'x0': self._transpile(node.left)} xes.update({'x%s' % (i + 1): self._transpile(node.comparators[i]) for i in range(len(node.comparators))}) return pat.format(**xes) raise ValueError('unrecognized expression node %s in "%s"' % (node.__class__.__name__, self.expr))
Example #26
Source File: debug.py From python-devtools with MIT License | 4 votes |
def _process_args(self, func_ast, code_lines, args, kwargs) -> 'Generator[DebugArgument, None, None]': # noqa: C901 import ast complex_nodes = ( ast.Call, ast.Attribute, ast.Subscript, ast.IfExp, ast.BoolOp, ast.BinOp, ast.Compare, ast.DictComp, ast.ListComp, ast.SetComp, ast.GeneratorExp, ) arg_offsets = list(self._get_offsets(func_ast)) for i, arg in enumerate(args): try: ast_node = func_ast.args[i] except IndexError: # pragma: no cover # happens when code has been commented out and there are fewer func_ast args than real args yield self.output_class.arg_class(arg) continue if isinstance(ast_node, ast.Name): yield self.output_class.arg_class(arg, name=ast_node.id) elif isinstance(ast_node, complex_nodes): # TODO replace this hack with astor when it get's round to a new release start_line, start_col = arg_offsets[i] if i + 1 < len(arg_offsets): end_line, end_col = arg_offsets[i + 1] else: end_line, end_col = len(code_lines) - 1, None name_lines = [] for l_ in range(start_line, end_line + 1): start_ = start_col if l_ == start_line else 0 end_ = end_col if l_ == end_line else None name_lines.append(code_lines[l_][start_:end_].strip(' ')) yield self.output_class.arg_class(arg, name=' '.join(name_lines).strip(' ,')) else: yield self.output_class.arg_class(arg) kw_arg_names = {} for kw in func_ast.keywords: if isinstance(kw.value, ast.Name): kw_arg_names[kw.arg] = kw.value.id for name, value in kwargs.items(): yield self.output_class.arg_class(value, name=name, variable=kw_arg_names.get(name))