Python ast.Raise() Examples
The following are 30
code examples of ast.Raise().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ast
, or try the search function
.
Example #1
Source File: exceptions.py From wemake-python-styleguide with MIT License | 6 votes |
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))
Example #2
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 6 votes |
def raise_stmt_ast_to_ir2(ast_node: ast.Raise, compilation_context: CompilationContext): if ast_node.cause: raise CompilationError(compilation_context, ast_node.cause, '"raise ... from ..." is not supported. Use a plain "raise ..." instead.') exception_expr = expression_ast_to_ir2(ast_node.exc, compilation_context, in_match_pattern=False, check_var_reference=lambda ast_node: None, match_lambda_argument_names=set(), current_stmt_line=ast_node.lineno) if not (isinstance(exception_expr.expr_type, ir2.CustomType) and exception_expr.expr_type.is_exception_class): if isinstance(exception_expr.expr_type, ir2.CustomType): custom_type_defn = compilation_context.get_type_symbol_definition(exception_expr.expr_type.name).ast_node notes = [(custom_type_defn, 'The type %s was defined here.' % exception_expr.expr_type.name)] else: notes = [] raise CompilationError(compilation_context, ast_node.exc, 'Can\'t raise an exception of type "%s", because it\'s not a subclass of Exception.' % str(exception_expr.expr_type), notes=notes) return ir2.RaiseStmt(expr=exception_expr, source_branch=SourceBranch(compilation_context.filename, ast_node.lineno, compilation_context.first_enclosing_except_stmt_line if compilation_context.first_enclosing_except_stmt_line else -compilation_context.current_function_definition_line))
Example #3
Source File: topython.py From pyrser with GNU General Public License v3.0 | 6 votes |
def __exit_scope(self) -> ast.stmt: """Create the appropriate scope exiting statement. The documentation only shows one level and always uses 'return False' in examples. 'raise AltFalse()' within a try. 'break' within a loop. 'return False' otherwise. """ if self.in_optional: return ast.Pass() if self.in_try: return ast.Raise( ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None), None) if self.in_loop: return ast.Break() return ast.Return(ast.Name('False', ast.Load())) #TODO(bps): find a better name to describe what this does
Example #4
Source File: core.py From vulture with MIT License | 6 votes |
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
Example #5
Source File: node_transformers.py From pynt with GNU General Public License v3.0 | 6 votes |
def visit_Return(self, return_): """Convert returns into assignment/exception pairs Since the body of this function will be in the global namespace we can't have any returns. An acceptable alternative is to set a variable called 'RETURN' and then immediately raise an exception. >>> self = NamespacePromoter(buffer='foo') >>> code = ''' ... ... return 5 ... ... ''' >>> tree = ast.parse(code) >>> return_, = tree.body """ nodes = [ ast.Assign(targets=[ast.Name(id='RETURN', ctx=ast.Store())], value=return_.value, lineno=return_.lineno), ast.Raise(exc=ast.Call(func=ast.Name(id='Exception', ctx=ast.Load()), args=[ast.Str(s='return')], keywords=[]), cause=None), ] return nodes
Example #6
Source File: onelinerizer.py From onelinerizer with MIT License | 6 votes |
def onelinerize(original): # original :: string # :: string t = ast.parse(original) table = symtable.symtable(original, '<string>', 'exec') original = original.strip() # If there's only one line anyways, be lazy if len(original.splitlines()) == 1 and \ len(t.body) == 1 and \ type(t.body[0]) in (ast.Delete, ast.Assign, ast.AugAssign, ast.Print, ast.Raise, ast.Assert, ast.Import, ast.ImportFrom, ast.Exec, ast.Global, ast.Expr, ast.Pass): return original return get_init_code(t, table)
Example #7
Source File: translation.py From mochi with MIT License | 5 votes |
def translate_raise(self, exp): if len(exp) != 2: raise MochiSyntaxError(exp, self.filename) return (ast.Raise(exc=self.translate(exp[1], False)[1], cause=None, lineno=exp[0].lineno, col_offset=0),), self.translate(EMPTY_SYM, False)[1]
Example #8
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_raise_stmt_2(p): '''raise_stmt : RAISE test''' # 1 2 p[0] = ast.Raise(p[2], None, None, rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #9
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_raise_stmt_3(p): '''raise_stmt : RAISE test COMMA test''' # 1 2 3 4 p[0] = ast.Raise(p[2], p[4], None, rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #10
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_raise_stmt_4(p): '''raise_stmt : RAISE test COMMA test COMMA test''' # 1 2 3 4 5 6 p[0] = ast.Raise(p[2], p[4], p[6], rule=inspect.currentframe().f_code.co_name, **p[1][1]) # import_stmt: import_name | import_from
Example #11
Source File: test_ast.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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")
Example #12
Source File: tree.py From dlint with BSD 3-Clause "New" or "Revised" License | 5 votes |
def function_is_empty(function): def raise_or_pass_or_docstring(node): return ( isinstance(node, ast.Raise) or isinstance(node, ast.Pass) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) ) return all( raise_or_pass_or_docstring(child) for child in function.body )
Example #13
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_Raise(self, node): ntype = self._visit(node.type) ninst = self._visit(node.inst) ntback = self._visit(node.tback) what = ntype if ninst is not None: what = gast.Call(ntype, [ninst], []) gast.copy_location(what, node) what.end_lineno = what.end_col_offset = None if ntback is not None: attr = gast.Attribute(what, 'with_traceback', gast.Load()) gast.copy_location(attr, node) attr.end_lineno = attr.end_col_offset = None what = gast.Call( attr, [ntback], [] ) gast.copy_location(what, node) what.end_lineno = what.end_col_offset = None new_node = gast.Raise(what, None) gast.copy_location(new_node, node) new_node.end_lineno = new_node.end_col_offset = None return new_node
Example #14
Source File: functions.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_generator(self, node: AnyFunctionDef) -> None: if not functions.is_generator(node): return for sub_node in walk.get_subnodes_by_type(node, ast.Raise): if exceptions.get_exception_name(sub_node) == 'StopIteration': self.add_violation( StopIterationInsideGeneratorViolation(sub_node), )
Example #15
Source File: keywords.py From wemake-python-styleguide with MIT License | 5 votes |
def visit_Raise(self, node: ast.Raise) -> None: """ Checks how ``raise`` keyword is used. Raises: RaiseNotImplementedViolation """ self._check_exception_type(node) self.generic_visit(node)
Example #16
Source File: keywords.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_exception_type(self, node: ast.Raise) -> None: exception_name = get_exception_name(node) if exception_name == 'NotImplemented': self.add_violation(RaiseNotImplementedViolation(node))
Example #17
Source File: exceptions.py From wemake-python-styleguide with MIT License | 5 votes |
def get_exception_name(node: ast.Raise) -> Optional[str]: """Returns the exception name or ``None`` if node has not it.""" exception = node.exc if exception is None: return None exception_func = getattr(exception, 'func', None) if exception_func: exception = exception_func return getattr(exception, 'id', None)
Example #18
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_raise_stmt_1(p): '''raise_stmt : RAISE''' # 1 p[0] = ast.Raise(None, None, None, rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #19
Source File: ast2.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_Raise(self, node): if isinstance(node.exc, gast.Call) and \ isinstance(node.exc.func, gast.Attribute) and \ node.exc.func.attr == 'with_traceback': raised = self._visit(node.exc.func.value) traceback = self._visit(node.exc.args[0]) else: raised = self._visit(node.exc) traceback = None new_node = ast.Raise(raised, None, traceback) ast.copy_location(new_node, node) return new_node
Example #20
Source File: function_description.py From darglint with MIT License | 5 votes |
def _get_all_raises(fn): # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> Iterator[ast.Raise] # noqa: E501 for node in ast.walk(fn): if isinstance(node, ast.Raise): yield node
Example #21
Source File: parser.py From myia with MIT License | 5 votes |
def raises(self, exc): """Raise an exception in this block.""" inputs = [Constant(primops.raise_), exc] raise_ = Apply(inputs, self.graph) self.returns(raise_)
Example #22
Source File: parser.py From myia with MIT License | 5 votes |
def process_Raise(self, block: "Block", node: ast.Raise) -> "Block": """Process a raise statement.""" block.raises(self.process_node(block, node.exc)) return block
Example #23
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 5 votes |
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")
Example #24
Source File: dead.py From dead with MIT License | 5 votes |
def _is_stub_function(self, node: ast.FunctionDef) -> bool: for stmt in node.body: if ( isinstance(stmt, ast.Expr) and isinstance(stmt.value, (ast.Str, ast.Ellipsis)) ): continue # docstring or ... elif isinstance(stmt, ast.Pass): continue # pass elif ( isinstance(stmt, ast.Raise) and stmt.cause is None and ( ( isinstance(stmt.exc, ast.Name) and stmt.exc.id in STUB_EXCEPTIONS ) or ( isinstance(stmt.exc, ast.Call) and isinstance(stmt.exc.func, ast.Name) and stmt.exc.func.id in STUB_EXCEPTIONS ) ) ): continue # raise NotImplementedError else: return False else: return True
Example #25
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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")
Example #26
Source File: pyupgrade.py From pyupgrade with MIT License | 5 votes |
def visit_Raise(self, node: ast.Raise) -> None: exc = node.exc if exc is not None and self._is_os_error_alias(exc): assert isinstance(exc, (ast.Name, ast.Attribute)) self.os_error_alias_simple[_ast_to_offset(exc)] = exc elif ( isinstance(exc, ast.Call) and self._is_os_error_alias(exc.func) ): self.os_error_alias_calls.add(_ast_to_offset(exc)) self.generic_visit(node)
Example #27
Source File: topython.py From pyrser with GNU General Public License v3.0 | 5 votes |
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]
Example #28
Source File: raise_visitor.py From darglint with MIT License | 5 votes |
def remove_exception(self, node): # type: (ast.Raise) -> None name = self._get_exception_name(node) if isinstance(name, str) and name in self.exceptions: self.exceptions.remove(name) self.handling = [name] elif isinstance(name, list): self.handling = [] for part in name: self.exceptions.remove(part) self.handling.append(part)
Example #29
Source File: raise_visitor.py From darglint with MIT License | 5 votes |
def add_exception(self, node): # type: (ast.Raise) -> Set[str] """Add an exception to the context. If the exception(s) doesn't have a name and doesn't have more children, then it's a bare raise. In that case, we return the exception(s) to the parent context. Args: node: A raise ast node. Returns: A list of exceptions to be passed up to the parent context. """ name = self._get_exception_name(node) if name == '': if self.in_bare_handler: return self.bare_handler_exceptions | self.exceptions else: return self.exceptions if isinstance(name, str): self.exceptions.add(name) elif isinstance(name, list): for part in name: self.exceptions.add(part) else: logger.warning('Node {} name extraction failed.') return []
Example #30
Source File: function_description.py From darglint with MIT License | 5 votes |
def _get_exception_name(raises): # type: (ast.Raise) -> str if isinstance(raises.exc, ast.Name): return raises.exc.id elif isinstance(raises.exc, ast.Call): if hasattr(raises.exc.func, 'id'): return getattr(raises.exc.func, 'id') elif hasattr(raises.exc.func, 'attr'): return getattr(raises.exc.func, 'attr') else: logger.debug( 'Raises function call has neither id nor attr.' 'has only: %s' % str(dir(raises.exc.func)) ) elif isinstance(raises.exc, ast.Attribute): return raises.exc.attr elif isinstance(raises.exc, ast.Subscript): id_repr = '' if hasattr(raises.exc.value, 'id'): id_repr = getattr(raises.exc.value, 'id') n_repr = '' if hasattr(raises.exc.slice, 'value'): value = getattr(raises.exc.slice, 'value') if hasattr(value, 'n'): n_repr = getattr(value, 'n') return '{}[{}]'.format( id_repr, n_repr, ) else: logger.debug('Unexpected type in raises expression: {}'.format( raises.exc )) return ''