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


Python ast.ExceptHandler方法代碼示例

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


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

示例1: get_statement_startend2

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def get_statement_startend2(lineno, node):
    import ast

    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    values = []
    for x in ast.walk(node):
        if isinstance(x, (ast.stmt, ast.ExceptHandler)):
            values.append(x.lineno - 1)
            for name in ("finalbody", "orelse"):
                val = getattr(x, name, None)
                if val:
                    # treat the finally/orelse part as its own statement
                    values.append(val[0].lineno - 1 - 1)
    values.sort()
    insert_index = bisect_right(values, lineno)
    start = values[insert_index - 1]
    if insert_index >= len(values):
        end = None
    else:
        end = values[insert_index]
    return start, end 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:24,代碼來源:source.py

示例2: visit_Try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [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

示例3: get_statement_startend2

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def get_statement_startend2(lineno: int, node: ast.AST) -> Tuple[int, Optional[int]]:
    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    values = []  # type: List[int]
    for x in ast.walk(node):
        if isinstance(x, (ast.stmt, ast.ExceptHandler)):
            values.append(x.lineno - 1)
            for name in ("finalbody", "orelse"):
                val = getattr(x, name, None)  # type: Optional[List[ast.stmt]]
                if val:
                    # treat the finally/orelse part as its own statement
                    values.append(val[0].lineno - 1 - 1)
    values.sort()
    insert_index = bisect_right(values, lineno)
    start = values[insert_index - 1]
    if insert_index >= len(values):
        end = None
    else:
        end = values[insert_index]
    return start, end 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:22,代碼來源:source.py

示例4: test_try

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [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: _iter_definitions

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [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

示例6: _maybe_update_variable

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def _maybe_update_variable(
        self,
        sub_node: _LocalVariable,
        var_name: str,
        local_variables: Dict[str, List[_LocalVariable]],
    ) -> None:
        defs = local_variables.get(var_name)
        if defs is not None:
            if not var_name or access.is_unused(var_name):
                # We check unused variable usage in a different place:
                # see `visitors/ast/naming.py`
                return
            defs.append(sub_node)
            return

        is_name_def = (
            isinstance(sub_node, ast.Name) and
            isinstance(sub_node.ctx, ast.Store)
        )

        if is_name_def or isinstance(sub_node, ast.ExceptHandler):
            local_variables[var_name] = [] 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:24,代碼來源:functions.py

示例7: _check_useless_except

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def _check_useless_except(self, node: ast.ExceptHandler) -> None:
        if len(node.body) != 1:
            return

        body = node.body[0]
        if not isinstance(body, ast.Raise):
            return

        if isinstance(body.exc, ast.Call):
            return

        if isinstance(body.exc, ast.Name) and node.name:
            if body.exc.id != node.name:
                return

        self.add_violation(UselessExceptCaseViolation(node)) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:18,代碼來源:exceptions.py

示例8: get_assigned_name

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def get_assigned_name(node: ast.AST) -> Optional[str]:
    """
    Returns variable names for node that is just assigned.

    Returns ``None`` for nodes that are used in a different manner.
    """
    if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
        return node.id

    if isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Store):
        return node.attr

    if isinstance(node, ast.ExceptHandler):
        return node.name

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

示例9: except_block_class_too_broad

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def except_block_class_too_broad(project_folder, *args, **kwargs):
    exception_type_to_catch = 'Exception'
    for parsed_file in project_folder.get_parsed_py_files():
        tryes = [node for node in ast.walk(parsed_file.ast_tree) if isinstance(node, ast.ExceptHandler)]
        for try_except in tryes:
            if try_except.type is None:
                return ''
            if (
                isinstance(try_except.type, ast.Name) and
                try_except.type.id == exception_type_to_catch
            ):
                message = _(
                    '%s class is too broad; use a more specific exception type'
                ) % exception_type_to_catch
                return message 
開發者ID:devmanorg,項目名稱:fiasko_bro,代碼行數:17,代碼來源:pythonic.py

示例10: try_stmt_rewrite

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [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

示例11: visit_Alt

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [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

示例12: visit_For

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def visit_For(self, loop_):
        """
        >>> self = FirstPassFor(buffer='foo')
        >>> code = '''
        ...
        ... for i in range(5):
        ...     for j in range(5):
        ...         k = i + j
        ...         print(k)
        ...
        ... '''
        >>> tree = ast.parse(code)
        >>> loop_, = tree.body

        """
        loop = self.generic_visit(loop_)
        var = ast.Name(id=__random_string__(), ctx=ast.Store())
        assign = ast.Assign(targets=[var], value=ast.Call(func=ast.Name(id='iter', ctx=ast.Load()), args=[loop.iter], keywords=[]))
        first_pass = ast.Try(
            body=[ast.Assign(targets=[loop.target], value=ast.Call(func=ast.Name(id='next', ctx=ast.Load()), args=[ast.Name(id=var, ctx=ast.Load())], keywords=[]))],
            handlers=[ast.ExceptHandler(type=ast.Name(id='StopIteration', ctx=ast.Load()), name=None, body=[ast.Pass()])],
            orelse=loop.body,
            finalbody=[]
        )
        content = f'`for {astor.to_source(loop.target).strip()} in {astor.to_source(loop.iter).strip()} ...`'
        return [
            make_annotation(buffer=self.buffer, content=content, cell_type='2', lineno=loop.lineno),
            ast.Expr(loop.iter),
            assign,
            first_pass
        ] 
開發者ID:ebanner,項目名稱:pynt,代碼行數:33,代碼來源:node_transformers.py

示例13: visit_Attribute

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def visit_Attribute(self, node):
        call_path = list(self.compose_call_path(node))
        if ".".join(call_path) == "sys.maxint":
            self.errors.append(B304(node.lineno, node.col_offset))
        elif len(call_path) == 2 and call_path[1] == "message":
            name = call_path[0]
            for elem in reversed(self.node_stack[:-1]):
                if isinstance(elem, ast.ExceptHandler) and elem.name == name:
                    self.errors.append(B306(node.lineno, node.col_offset))
                    break 
開發者ID:PyCQA,項目名稱:flake8-bugbear,代碼行數:12,代碼來源:bugbear.py

示例14: visit_ExceptHandler

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def visit_ExceptHandler(self, node):
        if node.name:
            new_node = gast.ExceptHandler(
                self._visit(node.type),
                gast.Name(node.name, gast.Store(), None, None),
                self._visit(node.body))
            ast.copy_location(new_node, node)
            return new_node
        else:
            return self.generic_visit(node) 
開發者ID:serge-sans-paille,項目名稱:gast,代碼行數:12,代碼來源:ast3.py

示例15: p_except_clause_1

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ExceptHandler [as 別名]
def p_except_clause_1(p):
    '''except_clause : EXCEPT'''
    #                       1
    p[0] = ast.ExceptHandler(None, None, [], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:6,代碼來源:hgawk_grammar.py


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