Python ast 模块,Raise() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用ast.Raise()

项目:vulture    作者:jendrikseipp    | 项目源码 | 文件源码
def _handle_ast_list(self, ast_list):
        """
        Find unreachable nodes in the given sequence of ast nodes.
        """
        for index, node in enumerate(ast_list):
            if isinstance(node, (ast.Break, ast.Continue, ast.Raise,
                                 ast.Return)):
                try:
                    first_unreachable_node = ast_list[index + 1]
                except IndexError:
                    continue
                class_name = node.__class__.__name__.lower()
                self._define(
                    self.unreachable_code,
                    class_name,
                    first_unreachable_node,
                    last_node=ast_list[-1],
                    message="unreachable code after '{class_name}'".format(
                        **locals()),
                    confidence=100)
                return
项目:fatoptimizer    作者:vstinner    | 项目源码 | 文件源码
def remove_dead_code(optimizer, node_list):
    """Remove dead code.

    Modify node_list in-place.
    Example: replace "return 1; return 2" with "return 1".
    """

    truncate = None
    stop = len(node_list) - 1
    for index, node in enumerate(node_list):
        if index == stop:
            break
        if not isinstance(node, (ast.Return, ast.Raise)):
            continue
        if not can_remove(node_list[index+1:]):
            continue
        truncate = index
        break
    # FIXME: use for/else: ?
    if truncate is None:
        return node_list
    optimizer.log_node_removal("Remove unreachable code", node_list[truncate+1:])
    return node_list[:truncate+1]
项目:mutpy    作者:mutpy    | 项目源码 | 文件源码
def get_coverable_nodes(cls):
        return {
            ast.Assert,
            ast.Assign,
            ast.AugAssign,
            ast.Break,
            ast.Continue,
            ast.Delete,
            ast.Expr,
            ast.Global,
            ast.Import,
            ast.ImportFrom,
            ast.Nonlocal,
            ast.Pass,
            ast.Raise,
            ast.Return,
            ast.FunctionDef,
            ast.ClassDef,
            ast.TryExcept,
            ast.TryFinally,
            ast.ExceptHandler,
            ast.If,
            ast.For,
            ast.While,
        }
项目:mutpy    作者:mutpy    | 项目源码 | 文件源码
def get_coverable_nodes(cls):
        return {
            ast.Assert,
            ast.Assign,
            ast.AugAssign,
            ast.Break,
            ast.Continue,
            ast.Delete,
            ast.Expr,
            ast.Global,
            ast.Import,
            ast.ImportFrom,
            ast.Nonlocal,
            ast.Pass,
            ast.Raise,
            ast.Return,
            ast.ClassDef,
            ast.FunctionDef,
            ast.Try,
            ast.ExceptHandler,
            ast.If,
            ast.For,
            ast.While,
        }
项目:peval    作者:fjarri    | 项目源码 | 文件源码
def filter_block(node_list):
    """
    Remove no-op code (``pass``), or any code after
    an unconditional jump (``return``, ``break``, ``continue``, ``raise``).
    """
    if len(node_list) == 1:
        return node_list

    new_list = []
    for node in node_list:
        if type(node) == ast.Pass:
            continue
        new_list.append(node)
        if type(node) in (ast.Return, ast.Break, ast.Continue, ast.Raise):
            break
    if len(new_list) == len(node_list):
        return node_list
    else:
        return new_list
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_Assert(self, t):
        return ast.If(t.test,
                      [],
                      [ast.Raise(Call(ast.Name('AssertionError', load),
                                      [] if t.msg is None else [t.msg]),
                                 None)])
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_Assert(self, t):
        t = self.generic_visit(t)
        result = ast.If(t.test,
                        [],
                        [ast.Raise(Call(ast.Name('AssertionError', load),
                                        [] if t.msg is None else [t.msg]),
                                   None)])
        return ast.copy_location(result, t)
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_Assert(self, t):
        t = self.generic_visit(t)
        result = ast.If(t.test,
                        [],
                        [ast.Raise(Call(ast.Name('AssertionError', load),
                                        [] if t.msg is None else [t.msg]),
                                   None)])
        return ast.copy_location(result, t)
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_Assert(self, t):
        t = self.generic_visit(t)
        result = ast.If(t.test,
                        [],
                        [ast.Raise(Call(ast.Name('AssertionError', load),
                                        [] if t.msg is None else [t.msg]),
                                   None)])
        return ast.copy_location(result, t)
项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def isStatement(a):
    """Determine whether the given node is a statement (vs an expression)"""
    return type(a) in [ ast.Module, ast.Interactive, ast.Expression, ast.Suite,
                        ast.FunctionDef, ast.ClassDef, ast.Return, ast.Delete,
                        ast.Assign, ast.AugAssign, ast.For, ast.While, 
                        ast.If, ast.With, ast.Raise, ast.Try, 
                        ast.Assert, ast.Import, ast.ImportFrom, ast.Global, 
                        ast.Expr, ast.Pass, ast.Break, ast.Continue ]
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_raise(self):
        r = ast.Raise(None, ast.Num(3))
        self.stmt(r, "Raise with cause but no exception")
        r = ast.Raise(ast.Name("x", ast.Store()), None)
        self.stmt(r, "must have Load context")
        r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
        self.stmt(r, "must have Load context")
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_raise(self):
        r = ast.Raise(None, ast.Num(3))
        self.stmt(r, "Raise with cause but no exception")
        r = ast.Raise(ast.Name("x", ast.Store()), None)
        self.stmt(r, "must have Load context")
        r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
        self.stmt(r, "must have Load context")
项目:mutpy    作者:mutpy    | 项目源码 | 文件源码
def mutate_ExceptHandler(self, node):
        if node.body and isinstance(node.body[0], ast.Raise):
            raise MutationResign()
        return ast.ExceptHandler(type=node.type, name=node.name, body=[ast.Raise()])
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_raise(self):
        r = ast.Raise(None, ast.Num(3))
        self.stmt(r, "Raise with cause but no exception")
        r = ast.Raise(ast.Name("x", ast.Store()), None)
        self.stmt(r, "must have Load context")
        r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
        self.stmt(r, "must have Load context")
项目:metapensiero.pj    作者:azazel75    | 项目源码 | 文件源码
def Raise(t, x):
    if x.exc is None:
        ename = t.ctx.get('ename')
        t.unsupported(x, not ename, "'raise' has no argument but failed obtaining"
                      " implicit exception")
        res = JSThrowStatement(JSName(ename))
    elif isinstance(x.exc, ast.Call) and isinstance(x.exc.func, ast.Name) and \
         len(x.exc.args) == 1 and x.exc.func.id == 'Exception':
        res = JSThrowStatement(JSNewCall(JSName('Error'), x.exc.args))
    else:
        res = JSThrowStatement(x.exc)

    return res
项目:peval    作者:fjarri    | 项目源码 | 文件源码
def handle_While(node, **_):
        last_node = node.body[-1]
        unconditional_jump = type(last_node) in (ast.Break, ast.Raise, ast.Return)
        if unconditional_jump and find_jumps(node.body) == 1:
            if type(last_node) == ast.Break:
                new_body = node.body[:-1]
            else:
                new_body = node.body
            return ast.If(test=node.test, body=new_body, orelse=node.orelse)
        else:
            return node
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def visit_Assert(self, assert_):
        """Return the AST statements to replace the ast.Assert instance.

        This re-writes the test of an assertion to provide
        intermediate values and replace it with an if statement which
        raises an assertion error with a detailed explanation in case
        the expression is false.

        """
        if isinstance(assert_.test, ast.Tuple) and self.config is not None:
            fslocation = (self.module_path, assert_.lineno)
            self.config.warn('R1', 'assertion is always true, perhaps '
                              'remove parentheses?', fslocation=fslocation)
        self.statements = []
        self.variables = []
        self.variable_counter = itertools.count()
        self.stack = []
        self.on_failure = []
        self.push_format_context()
        # Rewrite assert into a bunch of statements.
        top_condition, explanation = self.visit(assert_.test)
        # Create failure message.
        body = self.on_failure
        negation = ast.UnaryOp(ast.Not(), top_condition)
        self.statements.append(ast.If(negation, body, []))
        if assert_.msg:
            assertmsg = self.helper('format_assertmsg', assert_.msg)
            explanation = "\n>assert " + explanation
        else:
            assertmsg = ast.Str("")
            explanation = "assert " + explanation
        template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
        msg = self.pop_format_context(template)
        fmt = self.helper("format_explanation", msg)
        err_name = ast.Name("AssertionError", ast.Load())
        exc = ast_Call(err_name, [fmt], [])
        if sys.version_info[0] >= 3:
            raise_ = ast.Raise(exc, None)
        else:
            raise_ = ast.Raise(exc, None, None)
        body.append(raise_)
        # Clear temporary variables by setting them to None.
        if self.variables:
            variables = [ast.Name(name, ast.Store())
                         for name in self.variables]
            clear = ast.Assign(variables, _NameConstant(None))
            self.statements.append(clear)
        # Fix line numbers.
        for stmt in self.statements:
            set_location(stmt, assert_.lineno, assert_.col_offset)
        return self.statements
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def visit_Assert(self, assert_):
        """Return the AST statements to replace the ast.Assert instance.

        This re-writes the test of an assertion to provide
        intermediate values and replace it with an if statement which
        raises an assertion error with a detailed explanation in case
        the expression is false.

        """
        if isinstance(assert_.test, ast.Tuple) and self.config is not None:
            fslocation = (self.module_path, assert_.lineno)
            self.config.warn('R1', 'assertion is always true, perhaps '
                              'remove parentheses?', fslocation=fslocation)
        self.statements = []
        self.variables = []
        self.variable_counter = itertools.count()
        self.stack = []
        self.on_failure = []
        self.push_format_context()
        # Rewrite assert into a bunch of statements.
        top_condition, explanation = self.visit(assert_.test)
        # Create failure message.
        body = self.on_failure
        negation = ast.UnaryOp(ast.Not(), top_condition)
        self.statements.append(ast.If(negation, body, []))
        if assert_.msg:
            assertmsg = self.helper('format_assertmsg', assert_.msg)
            explanation = "\n>assert " + explanation
        else:
            assertmsg = ast.Str("")
            explanation = "assert " + explanation
        template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
        msg = self.pop_format_context(template)
        fmt = self.helper("format_explanation", msg)
        err_name = ast.Name("AssertionError", ast.Load())
        exc = ast_Call(err_name, [fmt], [])
        if sys.version_info[0] >= 3:
            raise_ = ast.Raise(exc, None)
        else:
            raise_ = ast.Raise(exc, None, None)
        body.append(raise_)
        # Clear temporary variables by setting them to None.
        if self.variables:
            variables = [ast.Name(name, ast.Store())
                         for name in self.variables]
            clear = ast.Assign(variables, _NameConstant(None))
            self.statements.append(clear)
        # Fix line numbers.
        for stmt in self.statements:
            set_location(stmt, assert_.lineno, assert_.col_offset)
        return self.statements
项目:godot-python    作者:touilleMan    | 项目源码 | 文件源码
def visit_Assert(self, assert_):
        """Return the AST statements to replace the ast.Assert instance.

        This re-writes the test of an assertion to provide
        intermediate values and replace it with an if statement which
        raises an assertion error with a detailed explanation in case
        the expression is false.

        """
        if isinstance(assert_.test, ast.Tuple) and self.config is not None:
            fslocation = (self.module_path, assert_.lineno)
            self.config.warn('R1', 'assertion is always true, perhaps '
                              'remove parentheses?', fslocation=fslocation)
        self.statements = []
        self.variables = []
        self.variable_counter = itertools.count()
        self.stack = []
        self.on_failure = []
        self.push_format_context()
        # Rewrite assert into a bunch of statements.
        top_condition, explanation = self.visit(assert_.test)
        # Create failure message.
        body = self.on_failure
        negation = ast.UnaryOp(ast.Not(), top_condition)
        self.statements.append(ast.If(negation, body, []))
        if assert_.msg:
            assertmsg = self.helper('format_assertmsg', assert_.msg)
            explanation = "\n>assert " + explanation
        else:
            assertmsg = ast.Str("")
            explanation = "assert " + explanation
        template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
        msg = self.pop_format_context(template)
        fmt = self.helper("format_explanation", msg)
        err_name = ast.Name("AssertionError", ast.Load())
        exc = ast_Call(err_name, [fmt], [])
        if sys.version_info[0] >= 3:
            raise_ = ast.Raise(exc, None)
        else:
            raise_ = ast.Raise(exc, None, None)
        body.append(raise_)
        # Clear temporary variables by setting them to None.
        if self.variables:
            variables = [ast.Name(name, ast.Store())
                         for name in self.variables]
            clear = ast.Assign(variables, _NameConstant(None))
            self.statements.append(clear)
        # Fix line numbers.
        for stmt in self.statements:
            set_location(stmt, assert_.lineno, assert_.col_offset)
        return self.statements
项目:godot-python    作者:touilleMan    | 项目源码 | 文件源码
def visit_Assert(self, assert_):
        """Return the AST statements to replace the ast.Assert instance.

        This re-writes the test of an assertion to provide
        intermediate values and replace it with an if statement which
        raises an assertion error with a detailed explanation in case
        the expression is false.

        """
        if isinstance(assert_.test, ast.Tuple) and self.config is not None:
            fslocation = (self.module_path, assert_.lineno)
            self.config.warn('R1', 'assertion is always true, perhaps '
                              'remove parentheses?', fslocation=fslocation)
        self.statements = []
        self.variables = []
        self.variable_counter = itertools.count()
        self.stack = []
        self.on_failure = []
        self.push_format_context()
        # Rewrite assert into a bunch of statements.
        top_condition, explanation = self.visit(assert_.test)
        # Create failure message.
        body = self.on_failure
        negation = ast.UnaryOp(ast.Not(), top_condition)
        self.statements.append(ast.If(negation, body, []))
        if assert_.msg:
            assertmsg = self.helper('format_assertmsg', assert_.msg)
            explanation = "\n>assert " + explanation
        else:
            assertmsg = ast.Str("")
            explanation = "assert " + explanation
        template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
        msg = self.pop_format_context(template)
        fmt = self.helper("format_explanation", msg)
        err_name = ast.Name("AssertionError", ast.Load())
        exc = ast_Call(err_name, [fmt], [])
        if sys.version_info[0] >= 3:
            raise_ = ast.Raise(exc, None)
        else:
            raise_ = ast.Raise(exc, None, None)
        body.append(raise_)
        # Clear temporary variables by setting them to None.
        if self.variables:
            variables = [ast.Name(name, ast.Store())
                         for name in self.variables]
            clear = ast.Assign(variables, _NameConstant(None))
            self.statements.append(clear)
        # Fix line numbers.
        for stmt in self.statements:
            set_location(stmt, assert_.lineno, assert_.col_offset)
        return self.statements
项目:GSM-scanner    作者:yosriayed    | 项目源码 | 文件源码
def visit_Assert(self, assert_):
        """Return the AST statements to replace the ast.Assert instance.

        This re-writes the test of an assertion to provide
        intermediate values and replace it with an if statement which
        raises an assertion error with a detailed explanation in case
        the expression is false.

        """
        self.statements = []
        self.variables = []
        self.variable_counter = itertools.count()
        self.stack = []
        self.on_failure = []
        self.push_format_context()
        # Rewrite assert into a bunch of statements.
        top_condition, explanation = self.visit(assert_.test)
        # Create failure message.
        body = self.on_failure
        negation = ast.UnaryOp(ast.Not(), top_condition)
        self.statements.append(ast.If(negation, body, []))
        if assert_.msg:
            assertmsg = self.helper('format_assertmsg', assert_.msg)
            explanation = "\n>assert " + explanation
        else:
            assertmsg = ast.Str("")
            explanation = "assert " + explanation
        template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
        msg = self.pop_format_context(template)
        fmt = self.helper("format_explanation", msg)
        err_name = ast.Name("AssertionError", ast.Load())
        exc = ast_Call(err_name, [fmt], [])
        if sys.version_info[0] >= 3:
            raise_ = ast.Raise(exc, None)
        else:
            raise_ = ast.Raise(exc, None, None)
        body.append(raise_)
        # Clear temporary variables by setting them to None.
        if self.variables:
            variables = [ast.Name(name, ast.Store())
                         for name in self.variables]
            clear = ast.Assign(variables, _NameConstant(None))
            self.statements.append(clear)
        # Fix line numbers.
        for stmt in self.statements:
            set_location(stmt, assert_.lineno, assert_.col_offset)
        return self.statements
项目:metapensiero.pj    作者:azazel75    | 项目源码 | 文件源码
def Try(t, x):
    t.unsupported(x, x.orelse, "'else' block of 'try' statement isn't supported")
    known_exc_types = (ast.Name, ast.Attribute, ast.Tuple, ast.List)
    ename = None
    if x.handlers:
        for h in x.handlers:
            if h.type is not None and not isinstance(h.type, known_exc_types):
                t.warn(x, "Exception type expression might not evaluate to a "
                       "valid type or sequence of types.")
            ename = h.name
        ename = ename or 'e'
        if t.has_child(x.handlers, ast.Raise) and t.has_child(x.finalbody, ast.Return):
            t.warn(x, node, "The re-raise in 'except' body may be masked by the "
                   "return in 'final' body.")
            # see
            # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#The_finally_block

        rhandlers = x.handlers.copy()
        rhandlers.reverse()
        prev_except = stmt =  None
        for ix, h in enumerate(rhandlers):
            body = h.body
            if h.name is not None and h.name != ename:
                # Rename the exception to match the handler
                rename = JSVarStatement([h.name], [ename])
                body = [rename] + h.body

            # if it's  the last except and it's a catchall
            # threat 'except Exception:' as a catchall
            if (ix == 0 and h.type is None or (isinstance(h.type, ast.Name) and
                                   h.type.id == 'Exception')):
                prev_except = JSStatements(*body)
                continue
            else:
                if ix == 0:
                    prev_except = JSThrowStatement(JSName(ename))
                # then h.type is an ast.Name != 'Exception'
                stmt = JSIfStatement(
                    _build_call_isinstance(JSName(ename), h.type),
                    body,
                    prev_except
                )
            prev_except = stmt
        t.ctx['ename'] = ename
        result = JSTryCatchFinallyStatement(x.body, ename, prev_except, x.finalbody)
    else:
        result = JSTryCatchFinallyStatement(x.body, None, None, x.finalbody)
    return result