我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用ast.Raise()。
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
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]
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, }
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, }
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
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)])
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)
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 ]
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")
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()])
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
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
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
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
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