本文整理匯總了Python中ast.Return方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.Return方法的具體用法?Python ast.Return怎麽用?Python ast.Return使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ast
的用法示例。
在下文中一共展示了ast.Return方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: visit
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def visit(self, node) -> Any:
if isinstance(node, ast.Name):
if isinstance(node.ctx, ast.Load):
self.loaded.add(node.id)
elif isinstance(node.ctx, ast.Store):
self.stored.add(node.id)
elif isinstance(node, ast.Return):
self.has_return = True
# We must keep track of importer name in order to avoid considering as variable
# names:
elif isinstance(node, ast.Import):
self.imported.update([ n.name for n in node.names])
elif isinstance(node, ast.ImportFrom):
self.imported.update([ n.name for n in node.names])
self.generic_visit(node)
示例2: _has_return
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _has_return(fun):
# type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool
"""Return true if the function has a fruitful return.
Args:
fun: A function node to check.
Returns:
True if there is a fruitful return, otherwise False.
"""
def skip(f):
return f != fun and isinstance(f, FunctionDef)
for node in _walk(fun, skip):
if isinstance(node, ast.Return) and node.value is not None:
return True
return False
示例3: return_stmt_ast_to_ir2
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def return_stmt_ast_to_ir2(ast_node: ast.Return,
compilation_context: CompilationContext):
expression = ast_node.value
if not expression:
raise CompilationError(compilation_context, ast_node,
'Return statements with no returned expression are not supported.')
expression = expression_ast_to_ir2(expression,
compilation_context,
in_match_pattern=False,
check_var_reference=lambda ast_node: None,
match_lambda_argument_names=set(),
current_stmt_line=ast_node.lineno)
return ir2.ReturnStmt(expr=expression,
source_branch=SourceBranch(compilation_context.filename,
ast_node.lineno,
-compilation_context.current_function_definition_line))
示例4: __exit_scope
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [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
示例5: _floodfill_nets
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _floodfill_nets( signal_list, adjacency ):
""" Floodfill to find out connected nets. Return a list of sets. """
nets = []
visited = set()
pred = {} # detect cycle that has >=3 nodes
for obj in signal_list:
# If obj has adjacent signals
if obj in adjacency and obj not in visited:
net = set()
Q = [ obj ]
while Q:
u = Q.pop()
visited.add( u )
net.add( u )
for v in adjacency[u]:
if v not in visited:
pred[v] = u
Q.append( v )
elif v is not pred[u]:
raise InvalidConnectionError(repr(v)+" is in a connection loop.")
if len(net) == 1:
continue
nets.append( net )
return nets
示例6: _create_labels
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _create_labels(loc_else=False):
"""Return the AST standing for label creations
@loc_else (optional): if set, create a label 'loc_else'"""
loc_end = "loc_end = ir.get_next_loc_key(instr)"
loc_end_expr = "loc_end_expr = ExprLoc(loc_end, ir.IRDst.size)"
out = ast.parse(loc_end).body
out += ast.parse(loc_end_expr).body
loc_if = "loc_if = ir.loc_db.add_location()"
loc_if_expr = "loc_if_expr = ExprLoc(loc_if, ir.IRDst.size)"
out += ast.parse(loc_if).body
out += ast.parse(loc_if_expr).body
if loc_else:
loc_else = "loc_else = ir.loc_db.add_location()"
loc_else_expr = "loc_else_expr = ExprLoc(loc_else, ir.IRDst.size)"
out += ast.parse(loc_else).body
out += ast.parse(loc_else_expr).body
return out
示例7: jump
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def jump(self, target: "Block", *args) -> Apply:
"""Jumping from one block to the next becomes a tail call.
This method will generate the tail call by calling the graph
corresponding to the target block using an `Apply` node, and returning
its value with a `Return` node. It will update the predecessor blocks
of the target appropriately.
Args:
target: The block to jump to from this statement.
"""
assert self.graph.return_ is None
jump = self.apply(target.graph, *args)
jump_call = jump
if self.use_universe:
jump_call = jump.inputs[1]
self.jumps[target] = jump_call
target.preds.append(self)
self.returns(jump)
示例8: check_for_b012
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def check_for_b012(self, node):
def _loop(node, bad_node_types):
if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
return
if isinstance(node, (ast.While, ast.For)):
bad_node_types = (ast.Return,)
elif isinstance(node, bad_node_types):
self.errors.append(B012(node.lineno, node.col_offset))
for child in ast.iter_child_nodes(node):
_loop(child, bad_node_types)
for child in node.finalbody:
_loop(child, (ast.Return, ast.Continue, ast.Break))
示例9: check_for_b901
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def check_for_b901(self, node):
if node.name == "__await__":
return
has_yield = False
return_node = None
for parent, x in self.walk_function_body(node):
# Only consider yield when it is part of an Expr statement.
if isinstance(parent, ast.Expr) and isinstance(
x, (ast.Yield, ast.YieldFrom)
):
has_yield = True
if isinstance(x, ast.Return) and x.value is not None:
return_node = x
if has_yield and return_node is not None:
self.errors.append(B901(return_node.lineno, return_node.col_offset))
break
示例10: _make_dict_elems
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _make_dict_elems(build_instr, builders):
"""
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
"""
keys = []
values = []
for _ in range(build_instr.arg):
popped = builders.pop()
if not isinstance(popped, instrs.STORE_MAP):
raise DecompilationError(
"Expected a STORE_MAP but got %s" % popped
)
keys.append(make_expr(builders))
values.append(make_expr(builders))
# Keys and values are emitted in reverse order of how they appear in the
# AST.
keys.reverse()
values.reverse()
return keys, values
示例11: _handle_ast_list
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [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
示例12: generic_visit
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def generic_visit(self, node):
super(NodeTransformer, self).generic_visit(node)
if hasattr(node, 'body') and type(node.body) is list:
returns = [i for i, child in enumerate(node.body) if type(child) is ast.Return]
if len(returns) > 0:
for wait in self.get_waits():
node.body.insert(returns[0], wait)
inserts = []
for i, child in enumerate(node.body):
if type(child) is ast.Expr and self.is_concurrent_call(child.value):
self.encounter_call(child.value)
elif self.is_valid_assignment(child):
call = child.value
self.encounter_call(call)
name = child.targets[0].value
self.arguments.add(SchedulerRewriter.top_level_name(name))
index = child.targets[0].slice.value
call.func = ast.Attribute(call.func, 'assign', ast.Load())
call.args = [ast.Tuple([name, index], ast.Load())] + call.args
node.body[i] = ast.Expr(call)
elif self.references_arg(child):
inserts.insert(0, i)
for index in inserts:
for wait in self.get_waits():
node.body.insert(index, wait)
示例13: _check_sub_node
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _check_sub_node(
self,
node: AnyFunctionDef,
sub_node: ast.AST,
) -> None:
if isinstance(sub_node, ast.Name):
if isinstance(sub_node.ctx, ast.Store):
self._update_variables(node, sub_node)
error_counters: _NodeTypeHandler = {
ast.Return: self.returns,
ast.Expr: self.expressions,
ast.Await: self.awaits,
ast.Assert: self.asserts,
}
for types, counter in error_counters.items():
if isinstance(sub_node, types):
counter[node] += 1
示例14: _check_last_return_in_function
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _check_last_return_in_function(self, node: ast.Return) -> None:
parent = get_parent(node)
if not isinstance(parent, FunctionNodes):
return
returns = len(tuple(filter(
lambda return_node: return_node.value is not None,
walk.get_subnodes_by_type(parent, ast.Return),
)))
last_value_return = (
len(parent.body) > 1 and
returns < 2 and
isinstance(node.value, ast.NameConstant) and
node.value.value is None
)
one_return_with_none = (
returns == 1 and
isinstance(node.value, ast.NameConstant) and
node.value.value is None
)
if node.value is None or last_value_return or one_return_with_none:
self.add_violation(InconsistentReturnViolation(node))
示例15: _get_previous_stmt
# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Return [as 別名]
def _get_previous_stmt(self, node: ast.Return) -> Optional[ast.stmt]:
"""
This method gets the previous node in a block.
It is kind of strange. Because nodes might have several bodies.
Like ``try`` or ``for`` or ``if`` nodes.
``return`` can also be the only statement there.
We also use ``cast`` for a reason.
Because ``return`` always has a parent.
"""
parent = cast(ast.AST, get_parent(node))
for part in ('body', 'orelse', 'finalbody'):
block = getattr(parent, part, [])
try:
current_index = block.index(node)
except ValueError:
continue
if current_index > 0:
return block[current_index - 1]
return None