def _wrap_in_loop(gen_sym, body_nodes, return_name):
new_bindings = dict()
return_flag, gen_sym = gen_sym('return_flag')
# Adding an explicit return at the end of the function, if it's not present.
if type(body_nodes[-1]) != ast.Return:
body_nodes = body_nodes + [ast.Return(value=NONE_NODE)]
inlined_code, returns_ctr, returns_in_loops = _replace_returns(
body_nodes, return_name, return_flag)
if returns_ctr == 1:
# A shortcut for a common case with a single return at the end of the function.
# No loop is required.
inlined_body = inlined_code[:-1]
else:
# Multiple returns - wrap in a `while` loop.
if returns_in_loops:
# `return_flag` value will be used to detect returns from nested loops
inlined_body = [
ast.Assign(
targets=[ast.Name(return_flag, ast.Store())],
value=FALSE_NODE)]
else:
inlined_body = []
inlined_body.append(
ast.While(
test=TRUE_NODE,
body=inlined_code,
orelse=[]))
return gen_sym, inlined_body, new_bindings
评论列表
文章目录