本文整理匯總了Python中ast.Raise方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.Raise方法的具體用法?Python ast.Raise怎麽用?Python ast.Raise使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ast
的用法示例。
在下文中一共展示了ast.Raise方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: raise_stmt_ast_to_ir2
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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))
示例2: __exit_scope
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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
示例3: visit_Return
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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
示例4: _handle_ast_list
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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
示例5: onelinerize
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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)
示例6: _check_useless_except
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [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))
示例7: _get_all_raises
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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
示例8: _get_exception_name
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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 ''
示例9: add_exception
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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 []
示例10: remove_exception
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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)
示例11: visit_Alt
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [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]
示例12: visit_Raise
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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)
示例13: test_raise
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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")
示例14: _is_stub_function
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
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
示例15: process_Raise
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Raise [as 別名]
def process_Raise(self, block: "Block", node: ast.Raise) -> "Block":
"""Process a raise statement."""
block.raises(self.process_node(block, node.exc))
return block