本文整理汇总了Python中ast.Try方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Try方法的具体用法?Python ast.Try怎么用?Python ast.Try使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Try方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: CONTINUE
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
示例2: visit_Try
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def visit_Try(self, node: ast.Try) -> None:
for handler in node.handlers:
htype = handler.type
if self._is_os_error_alias(htype):
assert isinstance(htype, (ast.Name, ast.Attribute))
self.os_error_alias_simple[_ast_to_offset(htype)] = htype
elif (
isinstance(htype, ast.Tuple) and
any(
self._is_os_error_alias(elt)
for elt in htype.elts
)
):
self.os_error_alias_excepts.add(_ast_to_offset(htype))
self.generic_visit(node)
示例3: visit_Try
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
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)
)
示例4: test_try
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
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")
示例5: CONTINUE
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, '_pyflakes_parent'):
n, n_child = n._pyflakes_parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody and not PY38_PLUS:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
示例6: _iter_definitions
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
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)
示例7: _find_returing_nodes
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def _find_returing_nodes(
node: ast.Try,
bad_returning_nodes: AnyNodes,
) -> Tuple[bool, bool, bool, bool]:
try_has = any(
is_contained(line, bad_returning_nodes)
for line in node.body
)
except_has = any(
is_contained(except_handler, bad_returning_nodes)
for except_handler in node.handlers
)
else_has = any(
is_contained(line, bad_returning_nodes)
for line in node.orelse
)
finally_has = any(
is_contained(line, bad_returning_nodes)
for line in node.finalbody
)
return try_has, except_has, else_has, finally_has
示例8: visit_Try
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def visit_Try(self, node: ast.Try) -> None:
"""
Used for find ``finally`` in ``try`` blocks without ``except``.
Raises:
UselessFinallyViolation
DuplicateExceptionViolation
TryExceptMultipleReturnPathViolation
IncorrectExceptOrderViolation
LoopControlFinallyViolation
"""
self._check_if_needs_except(node)
self._check_duplicate_exceptions(node)
self._check_return_path(node)
self._check_exception_order(node)
self._check_break_or_continue_in_finally(node)
self.generic_visit(node)
示例9: visit_statement_with_body
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def visit_statement_with_body(self, node: _StatementWithBody) -> None:
"""
Visits statement's body internals.
Raises:
UnreachableCodeViolation,
UselessNodeViolation
"""
self._check_internals(node.body)
if isinstance(node, self._nodes_with_orelse):
self._check_internals(node.orelse)
if isinstance(node, ast.Try):
self._check_internals(node.finalbody)
self._check_swapped_variables(node.body)
self._check_useless_node(node, node.body)
self.generic_visit(node)
示例10: _process_child_nodes
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def _process_child_nodes(
node: ast.AST,
increment_by: int,
complexity_calculator: Callable[[ast.AST, int], int],
) -> int:
child_complexity = 0
for node_num, child_node in enumerate(ast.iter_child_nodes(node)):
if isinstance(node, ast.Try):
if node_num == 1:
increment_by += 1 # add +1 for all try nodes except body
if node_num:
child_complexity += max(1, increment_by)
child_complexity += complexity_calculator(
child_node,
increment_by,
)
return child_complexity
示例11: getAlternatives
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def getAlternatives(n):
if isinstance(n, ast.If):
return [n.body]
if isinstance(n, ast.Try):
return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
示例12: try_stmt_rewrite
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
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)
示例13: is_try
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def is_try(node):
return hasattr(ast, "Try") and isinstance(node, ast.Try) or \
hasattr(ast, "TryExcept") and isinstance(node, ast.TryExcept) or \
hasattr(ast, "TryFinally") and isinstance(node, ast.TryFinally)
示例14: visit_Alt
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [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]
示例15: unpack
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Try [as 别名]
def unpack(code, namespace, lineno, only_first=True):
"""Extract the information out of a bunch of annotations
Args:
code (str) : the whole code buffer
namespace (str) : identifier for the region of code
lineno (int) : line number of the expression to unpack
only_first (bool) : only consider the first branch
>>> code = '''
...
... if 1:
... if 2:
... print(12)
...
... '''
>>>
>>> namespace = 'foo'
>>> lineno = 3
"""
tree = ast.parse(code)
small_tree = filter_away_except(tree, namespace)
shallow_tree = NamespacePromoter(buffer=namespace).visit(small_tree)
small_shallow_tree = ExpressionFinder(lineno).visit(shallow_tree)
expr_type, = small_shallow_tree.body
if isinstance(expr_type, ast.For):
unpacked = FirstPassForSimple(namespace).visit(small_shallow_tree)
elif isinstance(expr_type, ast.Try):
unpacked = UnpackTry(namespace, only_first).visit(small_shallow_tree)
else:
assert isinstance(expr_type, ast.If)
unpacked = UnpackIf(namespace).visit(small_shallow_tree)
annotations = ShallowAnnotator(namespace).visit(unpacked)
return unpack_annotations(annotations)