当前位置: 首页>>代码示例>>Python>>正文


Python ast.IfExp方法代码示例

本文整理汇总了Python中ast.IfExp方法的典型用法代码示例。如果您正苦于以下问题:Python ast.IfExp方法的具体用法?Python ast.IfExp怎么用?Python ast.IfExp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.IfExp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: visit_IfExp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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 
开发者ID:python-security,项目名称:pyt,代码行数:21,代码来源:transformer.py

示例2: process_IfExp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:mila-iqia,项目名称:myia,代码行数:21,代码来源:parser.py

示例3: handleNodeDelete

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:31,代码来源:checker.py

示例4: visit_Name

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:11,代码来源:rewrite.py

示例5: __ast_check_tail_recursive__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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)) 
开发者ID:baruchel,项目名称:lambdascript,代码行数:17,代码来源:__init__.py

示例6: visit_Name

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:11,代码来源:rewrite.py

示例7: test_ifexp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:7,代码来源:test_ast.py

示例8: test_correct_comparing

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:42,代码来源:expressions.py

示例9: visit_IfExp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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 
开发者ID:Parquery,项目名称:icontract,代码行数:13,代码来源:_recompute.py

示例10: handleNodeDelete

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:31,代码来源:checker.py

示例11: _eval

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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)) 
开发者ID:deep-fry,项目名称:mayo,代码行数:43,代码来源:parse.py

示例12: p_test_2

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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]) 
开发者ID:histogrammar,项目名称:histogrammar-python,代码行数:7,代码来源:hgawk_grammar.py

示例13: wrap_cell_expression

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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 
开发者ID:holoviz,项目名称:holoviews,代码行数:32,代码来源:preprocessors.py

示例14: _handle_conditional_node

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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,
                ) 
开发者ID:jendrikseipp,项目名称:vulture,代码行数:42,代码来源:core.py

示例15: handleNodeDelete

# 需要导入模块: import ast [as 别名]
# 或者: from ast import IfExp [as 别名]
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) 
开发者ID:QQuick,项目名称:Transcrypt,代码行数:31,代码来源:checker.py


注:本文中的ast.IfExp方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。