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


Python ast.Try方法代碼示例

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


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

示例1: CONTINUE

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, 'parent'):
            n, n_child = n.parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:24,代碼來源:checker.py

示例2: visit_Try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def visit_Try(self, node: ast.Try) -> None:
        for handler in node.handlers:
            htype = handler.type
            if self._is_os_error_alias(htype):
                assert isinstance(htype, (ast.Name, ast.Attribute))
                self.os_error_alias_simple[_ast_to_offset(htype)] = htype
            elif (
                    isinstance(htype, ast.Tuple) and
                    any(
                        self._is_os_error_alias(elt)
                        for elt in htype.elts
                    )
            ):
                self.os_error_alias_excepts.add(_ast_to_offset(htype))

        self.generic_visit(node) 
開發者ID:asottile,項目名稱:pyupgrade,代碼行數:18,代碼來源:pyupgrade.py

示例3: visit_Try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def visit_Try(self, try_):
        handlers = []
        for handler in try_.handlers:
            handlers.append(
                ast.ExceptHandler(
                    type=handler.type,
                    name=None,
                    body=self._annotate_nodes(handler.body)
                )
            )
        return ast.Try(
                body=self._annotate_nodes(try_.body),
                handlers=handlers,
                orelse=self._annotate_nodes(try_.orelse),
                finalbody=self._annotate_nodes(try_.finalbody)
        ) 
開發者ID:ebanner,項目名稱:pynt,代碼行數:18,代碼來源:node_transformers.py

示例4: test_try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def test_try(self):
        p = ast.Pass()
        t = ast.Try([], [], [], [p])
        self.stmt(t, "empty body on Try")
        t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
        self.stmt(t, "must have Load context")
        t = ast.Try([p], [], [], [])
        self.stmt(t, "Try has neither except handlers nor finalbody")
        t = ast.Try([p], [], [p], [p])
        self.stmt(t, "Try has orelse but no except handlers")
        t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
        self.stmt(t, "empty body on ExceptHandler")
        e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
        self.stmt(ast.Try([p], e, [], []), "must have Load context")
        e = [ast.ExceptHandler(None, "x", [p])]
        t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
        self.stmt(t, "must have Load context")
        t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
        self.stmt(t, "must have Load context") 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:21,代碼來源:test_ast.py

示例5: CONTINUE

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, '_pyflakes_parent'):
            n, n_child = n._pyflakes_parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody and not PY38_PLUS:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
開發者ID:PyCQA,項目名稱:pyflakes,代碼行數:24,代碼來源:checker.py

示例6: _iter_definitions

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def _iter_definitions(node):
    if isinstance(node, ast.Assign):
        for node in node.targets:
            while isinstance(node, ast.Attribute):
                node = node.value
            assert isinstance(node, ast.Name)
            yield node.id
    elif isinstance(node, (ast.FunctionDef, ast.ClassDef)):
        yield node.name
    elif isinstance(node, ast.If):
        for snode in node.body:
            yield from _iter_definitions(snode)
        for snode in node.orelse:
            yield from _iter_definitions(snode)
    elif isinstance(node, ast.Try):
        for snode in (node.body, node.finalbody, node.orelse):
            for ssnode in snode:
                yield from _iter_definitions(ssnode)
        for snode in node.handlers:
            assert isinstance(snode, ast.ExceptHandler)
            for ssnode in snode.body:
                yield from _iter_definitions(ssnode) 
開發者ID:s3ql,項目名稱:s3ql,代碼行數:24,代碼來源:checkpatch.py

示例7: _find_returing_nodes

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def _find_returing_nodes(
    node: ast.Try,
    bad_returning_nodes: AnyNodes,
) -> Tuple[bool, bool, bool, bool]:
    try_has = any(
        is_contained(line, bad_returning_nodes)
        for line in node.body
    )
    except_has = any(
        is_contained(except_handler, bad_returning_nodes)
        for except_handler in node.handlers
    )
    else_has = any(
        is_contained(line, bad_returning_nodes)
        for line in node.orelse
    )
    finally_has = any(
        is_contained(line, bad_returning_nodes)
        for line in node.finalbody
    )
    return try_has, except_has, else_has, finally_has 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:23,代碼來源:exceptions.py

示例8: visit_Try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def visit_Try(self, node: ast.Try) -> None:
        """
        Used for find ``finally`` in ``try`` blocks without ``except``.

        Raises:
            UselessFinallyViolation
            DuplicateExceptionViolation
            TryExceptMultipleReturnPathViolation
            IncorrectExceptOrderViolation
            LoopControlFinallyViolation

        """
        self._check_if_needs_except(node)
        self._check_duplicate_exceptions(node)
        self._check_return_path(node)
        self._check_exception_order(node)
        self._check_break_or_continue_in_finally(node)
        self.generic_visit(node) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:20,代碼來源:exceptions.py

示例9: visit_statement_with_body

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def visit_statement_with_body(self, node: _StatementWithBody) -> None:
        """
        Visits statement's body internals.

        Raises:
            UnreachableCodeViolation,
            UselessNodeViolation

        """
        self._check_internals(node.body)
        if isinstance(node, self._nodes_with_orelse):
            self._check_internals(node.orelse)
        if isinstance(node, ast.Try):
            self._check_internals(node.finalbody)

        self._check_swapped_variables(node.body)
        self._check_useless_node(node, node.body)
        self.generic_visit(node) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:20,代碼來源:statements.py

示例10: _process_child_nodes

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def _process_child_nodes(
    node: ast.AST,
    increment_by: int,
    complexity_calculator: Callable[[ast.AST, int], int],
) -> int:
    child_complexity = 0

    for node_num, child_node in enumerate(ast.iter_child_nodes(node)):
        if isinstance(node, ast.Try):
            if node_num == 1:
                increment_by += 1  # add +1 for all try nodes except body
            if node_num:
                child_complexity += max(1, increment_by)
        child_complexity += complexity_calculator(
            child_node,
            increment_by,
        )

    return child_complexity 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:21,代碼來源:cognitive.py

示例11: getAlternatives

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def getAlternatives(n):
        if isinstance(n, ast.If):
            return [n.body]
        if isinstance(n, ast.Try):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:7,代碼來源:checker.py

示例12: try_stmt_rewrite

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def try_stmt_rewrite(mark, body, excs, rescues, orelse, final):
    excs = excs or []
    rescues = rescues or []

    def handlers():
        for (type, name), body in zip(excs, rescues):
            yield ast.ExceptHandler(type, name, body)

    return ast.Try(body, list(handlers()), orelse or [], final or [], **loc @ mark) 
開發者ID:Xython,項目名稱:YAPyPy,代碼行數:11,代碼來源:helper.py

示例13: is_try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def is_try(node):
        return hasattr(ast, "Try") and isinstance(node, ast.Try) or \
               hasattr(ast, "TryExcept") and isinstance(node, ast.TryExcept) or \
               hasattr(ast, "TryFinally") and isinstance(node, ast.TryFinally) 
開發者ID:danhper,項目名稱:bigcode-tools,代碼行數:6,代碼來源:ast_generator.py

示例14: visit_Alt

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def visit_Alt(self, node: parsing.Alt) -> [ast.stmt]:
        """Generates python code for alternatives.

        try:
            try:
                <code for clause>  #raise AltFalse when alternative is False
                raise AltTrue()
            except AltFalse:
                pass
            return False
        except AltTrue:
            pass
        """
        clauses = [self.visit(clause) for clause in node.ptlist]
        for clause in clauses:
            if not isinstance(clause, ast.expr):
                break
        else:
            return ast.BoolOp(ast.Or(), clauses)
        res = ast.Try([], [ast.ExceptHandler(
            ast.Name('AltTrue', ast.Load()), None, [ast.Pass()])], [], [])
        alt_true = [ast.Raise(ast.Call(
            ast.Name('AltTrue', ast.Load()), [], [], None, None), None)]
        alt_false = [ast.ExceptHandler(
            ast.Name('AltFalse', ast.Load()), None, [ast.Pass()])]
        self.in_try += 1
        for clause in node.ptlist:
            res.body.append(
                ast.Try(self._clause(self.visit(clause)) + alt_true,
                        alt_false, [], []))
        self.in_try -= 1
        res.body.append(self.__exit_scope())
        return [res] 
開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:35,代碼來源:topython.py

示例15: unpack

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Try [as 別名]
def unpack(code, namespace, lineno, only_first=True):
    """Extract the information out of a bunch of annotations

    Args:
        code (str) : the whole code buffer
        namespace (str) : identifier for the region of code
        lineno (int) : line number of the expression to unpack
        only_first (bool) : only consider the first branch

    >>> code = '''
    ...
    ... if 1:
    ...     if 2:
    ...         print(12)
    ...
    ... '''
    >>>
    >>> namespace = 'foo'
    >>> lineno = 3

    """
    tree = ast.parse(code)
    small_tree = filter_away_except(tree, namespace)
    shallow_tree = NamespacePromoter(buffer=namespace).visit(small_tree)
    small_shallow_tree = ExpressionFinder(lineno).visit(shallow_tree)
    expr_type, = small_shallow_tree.body
    if isinstance(expr_type, ast.For):
        unpacked = FirstPassForSimple(namespace).visit(small_shallow_tree)
    elif isinstance(expr_type, ast.Try):
        unpacked = UnpackTry(namespace, only_first).visit(small_shallow_tree)
    else:
        assert isinstance(expr_type, ast.If)
        unpacked = UnpackIf(namespace).visit(small_shallow_tree)
    annotations = ShallowAnnotator(namespace).visit(unpacked)
    return unpack_annotations(annotations) 
開發者ID:ebanner,項目名稱:pynt,代碼行數:37,代碼來源:syntax.py


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