當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.If方法代碼示例

本文整理匯總了Python中ast.If方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.If方法的具體用法?Python ast.If怎麽用?Python ast.If使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.If方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: indent_not_multiple_of_tab_size

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def indent_not_multiple_of_tab_size(project_folder, tab_size, *args, **kwargs):
    """
        Since there are cases for which col_offset is computed incorrectly,
        this validator must be nothing more than a simple warning.

        It compliments the pep8 validator which tends to fail in cases when
        the indent is incorrect.
    """
    node_types_to_validate = (ast.For, ast.If, ast.FunctionDef, ast.With)
    for parsed_file in project_folder.get_parsed_py_files():
        lines_offsets = file_helpers.get_line_offsets(parsed_file.content)
        for node in ast.walk(parsed_file.ast_tree):
            if not ast_helpers.is_node_offset_fine(
                node,
                lines_offsets,
                node_types_to_validate,
                tab_size,
            ):
                return parsed_file.get_name_with_line(node.lineno) 
開發者ID:devmanorg,項目名稱:fiasko_bro,代碼行數:21,代碼來源:syntax.py

示例2: _find_sub_setup_call

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def _find_sub_setup_call(
        self, elements
    ):  # type: (List[Any]) -> Tuple[Optional[ast.Call], Optional[List[Any]]]
        for element in elements:
            if not isinstance(element, (ast.FunctionDef, ast.If)):
                continue

            setup_call = self._find_setup_call(element.body)
            if setup_call != (None, None):
                setup_call, body = setup_call

                body = elements + body

                return setup_call, body

        return None, None 
開發者ID:python-poetry,項目名稱:poetry,代碼行數:18,代碼來源:setup_reader.py

示例3: visit_Rep0N

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]:
        """Generates python code for a clause repeated 0 or more times.

        #If all clauses can be inlined
        while clause:
            pass

        while True:
            <code for the clause>
        """
        cl_ast = self.visit(node.pt)
        if isinstance(cl_ast, ast.expr):
            return [ast.While(cl_ast, [ast.Pass()], [])]
        self.in_loop += 1
        clause = self._clause(self.visit(node.pt))
        self.in_loop -= 1
        return [ast.While(ast.Name('True', ast.Load()), clause, [])] 
開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:19,代碼來源:topython.py

示例4: get_source

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def get_source(self):
        """
        Get a string containing the Python source code corresponding to the
        statements in the block.

        Returns:
            A string containing the source code of the statements.
        """
        src = ""
        for statement in self.statements:
            if type(statement) in [ast.If, ast.For, ast.While]:
                src += (astor.to_source(statement)).split('\n')[0] + "\n"
            elif type(statement) == ast.FunctionDef or\
                 type(statement) == ast.AsyncFunctionDef:
                src += (astor.to_source(statement)).split('\n')[0] + "...\n"
            else:
                src += astor.to_source(statement)
        return src 
開發者ID:coetaur0,項目名稱:staticfg,代碼行數:20,代碼來源:model.py

示例5: visit_Module

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def visit_Module(self, module):
        """Maybe replace the entire module with a kernel

        If namespace is targeting the top-level then we do it.

        >>> self = IPythonEmbedder(namespace='foo.foo')
        >>> code = '''
        ...
        ... import random
        ... def foo():
        ...     pass
        ...
        ... '''
        >>> module = ast.parse(code)

        """
        if self.func_type == 'module':
            module.body = self.get_kernel_embed()
        else:
            module = self.generic_visit(module)
        return module 
開發者ID:ebanner,項目名稱:pynt,代碼行數:23,代碼來源:node_transformers.py

示例6: handle_or_else

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def handle_or_else(self, orelse, test):
        """Handle the orelse part of an if or try node.

        Args:
            orelse(list[Node])
            test(Node)

        Returns:
            The last nodes of the orelse branch.
        """
        if isinstance(orelse[0], ast.If):
            control_flow_node = self.visit(orelse[0])
            # Prefix the if label with 'el'
            control_flow_node.test.label = 'el' + control_flow_node.test.label

            test.connect(control_flow_node.test)
            return control_flow_node.last_nodes
        else:
            else_connect_statements = self.stmt_star_handler(
                orelse,
                prev_node_to_avoid=self.nodes[-1]
            )
            test.connect(else_connect_statements.first_statement)
            return else_connect_statements.last_statements 
開發者ID:python-security,項目名稱:pyt,代碼行數:26,代碼來源:stmt_visitor.py

示例7: _translate_if

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def _translate_if(self, test, orelse, body, location, base=True):
        test_node = self._testable(self._translate_node(test))
        block = self._translate_node(body)
        #block [self._translate_node(child) for child in body]
        if orelse and len(orelse) == 1 and isinstance(orelse[0], ast.If):
            otherwise = self._translate_if(orelse[0].test, orelse[0].orelse, orelse[0].body, location, False)
        elif orelse:
            otherwise = {
                'type': 'else_statement',
                'block': self._translate_node(orelse),
                #block [self._translate_node(node) for node in orelse],
                'pseudo_type': 'Void'
            }
        else:
            otherwise = None

        return {
            'type': 'if_statement' if base else 'elseif_statement',
            'test': test_node,
            'block': block,
            'pseudo_type': 'Void',
            'otherwise': otherwise
        } 
開發者ID:pseudo-lang,項目名稱:pseudo-python,代碼行數:25,代碼來源:ast_translator.py

示例8: while_

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def while_(self, block, src):
    #Mark the start and stop indices for the while condition so it can be checked later
    start_index = len(block.code)
    #Parse the condition
    cond = self.expression(block, src.test)
    #Generate the mask
    mask = self.get_mask(block, cond, Operator.bit_and)
    stop_index = len(block.code)
    loop = WhileLoop(mask)
    #Recursively parse the body
    for stmt in src.body:
      self.statement(loop.block, stmt)
    #Duplicate the condition checking code
    self.add_comment(loop.block, src)
    loop.block.code += block.code[start_index:stop_index]
    #Nest the loop in the current block
    block.add(loop)

  #Parses an if(-else) statement (AST If) 
開發者ID:undefx,項目名稱:vecpy,代碼行數:21,代碼來源:parser.py

示例9: make_assignment

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def make_assignment(instr, queue, stack):
    """
    Make an ast.Assign node.
    """
    value = make_expr(stack)

    # Make assignment targets.
    # If there are multiple assignments (e.g. 'a = b = c'),
    # each LHS expression except the last is preceded by a DUP_TOP instruction.
    # Thus, we make targets until we don't see a DUP_TOP, and then make one
    # more.
    targets = []
    while isinstance(instr, instrs.DUP_TOP):
        targets.append(make_assign_target(queue.popleft(), queue, stack))
        instr = queue.popleft()

    targets.append(make_assign_target(instr, queue, stack))

    return ast.Assign(targets=targets, value=value) 
開發者ID:llllllllll,項目名稱:codetransformer,代碼行數:21,代碼來源:_343.py

示例10: visit_If

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def visit_If(self, node: ast.If) -> None:
        # have is, is not already, not clear If directly is a valuable mutation
        print(f"If: {node}")
        print(ast.dump(node))
        self.generic_visit(node) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:7,代碼來源:_devtools.py

示例11: __init__

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def __init__(
        self,
        target_idx: Optional[LocIndex] = None,
        mutation: Optional[Any] = None,
        readonly: bool = False,
        src_file: Optional[Union[Path, str]] = None,
    ) -> None:
        """Create the AST node transformer for mutations.

        If readonly is set to True then no transformations are applied;
        however, the locs attribute is updated with the locations of nodes that could
        be transformed. This allows the class to function both as an inspection method
        and as a mutation transformer.

        Note that different nodes handle the ``LocIndex`` differently based on the context. For
        example, ``visit_BinOp`` uses direct AST types, while ``visit_NameConstant`` uses values,
        and ``visit_AugAssign`` uses custom strings in a dictionary mapping.

        All ``visit_`` methods take the ``node`` as an argument and rely on the class properties.

        This MutateBase class is designed to be implemented with the appropriate Mixin Class
        for supporting either Python 3.7 or Python 3.8 ASTs. If the base class is used
        directly certain operations - like ``visit_If`` and ``visit_NameConstant`` will not
        work as intended..

        Args:
            target_idx: Location index for the mutatest in the AST
            mutation: the mutatest to apply, may be a type or a value
            readonly: flag for read-only operations, used to visit nodes instead of transform
            src_file: Source file name, used for logging purposes
        """
        self.locs: Set[LocIndex] = set()

        # managed via @property
        self._target_idx = target_idx
        self._mutation = mutation
        self._readonly = readonly
        self._src_file = src_file 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:40,代碼來源:transformers.py

示例12: flattenIf

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def flattenIf(self, node, tests, else_, co):
        """ Flatten if-then-else as in compiler package."""
        if node:
            if len(node) == 1 and \
                    isinstance(node[0], ast.If) and \
                    node[0].body[0].col_offset == co:  # ugly hack to detect separate else clause
                elifnode = node[0]
                tests.append((elifnode.test, elifnode.body))
                self.flattenIf(elifnode.orelse, tests, else_, co)
            else:
                else_[:] = node 
開發者ID:myhdl,項目名稱:myhdl,代碼行數:13,代碼來源:_analyze.py

示例13: manageEdges

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def manageEdges(self, ifnode, senslist):
        """ Helper method to convert MyHDL style template into VHDL style"""
        first = senslist[0]
        if isinstance(first, _WaiterList):
            bt = _WaiterList
        elif isinstance(first, _Signal):
            bt = _Signal
        elif isinstance(first, delay):
            bt = delay
        assert bt
        for e in senslist:
            if not isinstance(e, bt):
                self.raiseError(ifnode, "base type error in sensitivity list")
        if len(senslist) >= 2 and bt == _WaiterList:
            # ifnode = node.code.nodes[0]
            # print ifnode
            assert isinstance(ifnode, ast.If)
            asyncEdges = []
            for test, suite in ifnode.tests:
                e = self.getEdge(test)
                if e is None:
                    self.raiseError(ifnode, "No proper edge value test")
                asyncEdges.append(e)
            if not ifnode.else_:
                self.raiseError(ifnode, "No separate else clause found")
            edges = []
            for s in senslist:
                for e in asyncEdges:
                    if s is e:
                        break
                else:
                    edges.append(s)
            ifnode.edge = edges
            senslist = [s.sig for s in senslist]
        return senslist 
開發者ID:myhdl,項目名稱:myhdl,代碼行數:37,代碼來源:_toVHDL.py

示例14: _ifchain

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def _ifchain(state, stmt, chain):
    test = _expression(stmt.test, _newscope(state))
    thenClause = _statements(stmt.body, _newscope(state))
    chain.append(OrderedDict([("if", test), ("then", thenClause)]))

    if len(stmt.orelse) == 0:
        return chain

    elif len(stmt.orelse) == 1 and isinstance(stmt.orelse[0], ast.If):
        return _ifchain(state, stmt.orelse[0], chain)

    else:
        chain.append(_statements(stmt.orelse, _newscope(state)))
        return chain 
開發者ID:modelop,項目名稱:hadrian,代碼行數:16,代碼來源:expression.py

示例15: is_has_local_imports

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import If [as 別名]
def is_has_local_imports(tree):
    imports = get_all_imports(tree)
    for import_node in imports:
        if not import_node.col_offset:
            continue
        if isinstance(import_node.parent, ast.If) and not import_node.parent.col_offset:
            continue
        return True
    return False 
開發者ID:devmanorg,項目名稱:fiasko_bro,代碼行數:11,代碼來源:ast_helpers.py


注:本文中的ast.If方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。