Python ast.ExceptHandler() Examples
The following are 28
code examples of ast.ExceptHandler().
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: helper.py From YAPyPy with MIT License | 6 votes |
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)
Example #2
Source File: name_nodes.py From wemake-python-styleguide with MIT License | 6 votes |
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
Example #3
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 #4
Source File: functions.py From wemake-python-styleguide with MIT License | 6 votes |
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] = []
Example #5
Source File: checkpatch.py From s3ql with GNU General Public License v3.0 | 6 votes |
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)
Example #6
Source File: test_ast.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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")
Example #7
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 6 votes |
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")
Example #8
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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")
Example #9
Source File: node_transformers.py From pynt with GNU General Public License v3.0 | 6 votes |
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) )
Example #10
Source File: source.py From pytest with MIT License | 6 votes |
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
Example #11
Source File: source.py From python-netsurv with MIT License | 6 votes |
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
Example #12
Source File: source.py From python-netsurv with MIT License | 6 votes |
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
Example #13
Source File: pythonic.py From fiasko_bro with MIT License | 5 votes |
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
Example #14
Source File: predicates.py From wemake-python-styleguide with MIT License | 5 votes |
def is_same_try_except_cases(node: ast.AST, names: Set[str]) -> bool: """Same names in different ``except`` blocks are not counted.""" if not isinstance(node, ast.ExceptHandler): return False for except_handler in getattr(get_parent(node), 'handlers', []): if except_handler.name and except_handler.name == node.name: if except_handler is not node: return True return False
Example #15
Source File: blocks.py From wemake-python-styleguide with MIT License | 5 votes |
def visit_named_nodes( self, node: Union[AnyFunctionDef, ast.ClassDef, ast.ExceptHandler], ) -> None: """ Visits block nodes that have ``.name`` property. Raises: BlockAndLocalOverlapViolation """ names = {node.name} if node.name else set() self._scope(node, names, is_local=False) self._outer_scope(node, names) self.generic_visit(node)
Example #16
Source File: exceptions.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_exception_type(self, node: ast.ExceptHandler) -> None: exception_name = node.type if exception_name is None: return exception_id = getattr(exception_name, 'id', None) if exception_id == self._base_exception: self.add_violation(BaseExceptionViolation(node))
Example #17
Source File: exceptions.py From wemake-python-styleguide with MIT License | 5 votes |
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: """ Checks all ``ExceptionHandler`` nodes. Raises: BaseExceptionViolation UselessExceptCaseViolation """ self._check_useless_except(node) self._check_exception_type(node) self.generic_visit(node)
Example #18
Source File: functions.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_unused_variables(self, node: AnyFunctionDef) -> None: local_variables: Dict[str, List[_LocalVariable]] = {} for body_item in node.body: for sub_node in ast.walk(body_item): if isinstance(sub_node, (ast.Name, ast.ExceptHandler)): var_name = self._get_variable_name(sub_node) self._maybe_update_variable( sub_node, var_name, local_variables, ) self._ensure_used_variables(local_variables)
Example #19
Source File: translation.py From mochi with MIT License | 5 votes |
def _translate_handler(self, exp): type_expr, var, *body = exp return ast.ExceptHandler(type=self.translate(type_expr, False)[1], name=var.name, body=self._translate_sequence(body, True), lineno=var.lineno, col_offset=0)
Example #20
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 #21
Source File: node_transformers.py From pynt with GNU General Public License v3.0 | 5 votes |
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 ]
Example #22
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_except_clause_4(p): '''except_clause : EXCEPT test COMMA test''' # 1 2 3 4 ctx_to_store(p[4]) p[0] = ast.ExceptHandler(p[2], p[4], [], rule=inspect.currentframe().f_code.co_name, **p[1][1]) # suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
Example #23
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_except_clause_3(p): '''except_clause : EXCEPT test AS test''' # 1 2 3 4 ctx_to_store(p[4]) p[0] = ast.ExceptHandler(p[2], p[4], [], rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #24
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_except_clause_2(p): '''except_clause : EXCEPT test''' # 1 2 p[0] = ast.ExceptHandler(p[2], None, [], rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #25
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
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])
Example #26
Source File: ast3.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_ExceptHandler(self, node): if node.name: new_node = ast.ExceptHandler( self._visit(node.type), node.name.id, self._visit(node.body)) return ast.copy_location(new_node, node) else: return self.generic_visit(node)
Example #27
Source File: ast3.py From gast with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #28
Source File: bugbear.py From flake8-bugbear with MIT License | 5 votes |
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