当前位置: 首页>>代码示例>>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;未经允许,请勿转载。