本文整理汇总了Python中ast.For方法的典型用法代码示例。如果您正苦于以下问题:Python ast.For方法的具体用法?Python ast.For怎么用?Python ast.For使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.For方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: indent_not_multiple_of_tab_size
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def indent_not_multiple_of_tab_size(project_folder, tab_size, *args, **kwargs):
"""
Since there are cases for which col_offset is computed incorrectly,
this validator must be nothing more than a simple warning.
It compliments the pep8 validator which tends to fail in cases when
the indent is incorrect.
"""
node_types_to_validate = (ast.For, ast.If, ast.FunctionDef, ast.With)
for parsed_file in project_folder.get_parsed_py_files():
lines_offsets = file_helpers.get_line_offsets(parsed_file.content)
for node in ast.walk(parsed_file.ast_tree):
if not ast_helpers.is_node_offset_fine(
node,
lines_offsets,
node_types_to_validate,
tab_size,
):
return parsed_file.get_name_with_line(node.lineno)
示例2: get_source
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def get_source(self):
"""
Get a string containing the Python source code corresponding to the
statements in the block.
Returns:
A string containing the source code of the statements.
"""
src = ""
for statement in self.statements:
if type(statement) in [ast.If, ast.For, ast.While]:
src += (astor.to_source(statement)).split('\n')[0] + "\n"
elif type(statement) == ast.FunctionDef or\
type(statement) == ast.AsyncFunctionDef:
src += (astor.to_source(statement)).split('\n')[0] + "...\n"
else:
src += astor.to_source(statement)
return src
示例3: visit_IfExp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def visit_IfExp( self, node ):
self.only_loop_at_top &= (self.loop_stack > 0)
# Special case "if s.reset:" -- it's only high for a cycle
if isinstance( node.test, ast.Attribute ) and \
node.test.attr == 'reset' and \
isinstance( node.test.value, ast.Name ) and \
node.test.value.id == 's':
pass
else:
self.num_br += 1
self.visit( node.test )
self.visit( node.body )
self.visit( node.orelse )
# For/while is fine
示例4: visit_Name
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def visit_Name(self, node):
# If it is from the argument list or loop variable, we do not worry about it!
if node.id in self._args.keys():
return
fors = [loop.target.id for loop in self.scope_level if isinstance(loop, ast.For)]
if node.id in fors:
return
# The loop variable cannot be overwritten when iteration
if isinstance(node.ctx, ast.Store) and node.id in fors:
raise ValueError("Iter var cannot be overwritten")
if node.id not in self.status.keys():
if not isinstance(node.ctx, ast.Store):
raise ValueError('In Python, "first store" indicates "declaration"')
self.status[node.id] = (node, self.scope_level[-1], set())
else:
decl, loop, usage = self.status[node.id]
usage.add(type(node.ctx))
self.status[node.id] = (decl, loop, usage)
示例5: test_node_types
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def test_node_types(self):
"""
Test that the typeable node types are collected
"""
visitor = self._run_visitor(
"""\
x = 1 # assignment
for x in range(1): pass # for loop
def f(): pass # function definition
with a as b: pass # with statement
"""
)
self.assertEqual(visitor.typeable_lines, [1, 2, 3, 4])
self.assertIsInstance(visitor.typeable_nodes[1], ast.Assign)
self.assertIsInstance(visitor.typeable_nodes[2], ast.For)
self.assertIsInstance(visitor.typeable_nodes[3], ast.FunctionDef)
self.assertIsInstance(visitor.typeable_nodes[4], ast.With)
示例6: check_for_b012
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [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))
示例7: gen_aug_assign
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def gen_aug_assign(self, statement):
""" Compile augmented assign.
For example: 'a += 2'
"""
target = statement.target
if isinstance(target, ast.Name):
name = target.id
assert isinstance(name, str)
var = self.get_variable(target, name)
assert var.lvalue
lhs = self.builder.emit_load(var.value, var.ty)
rhs = self.gen_expr(statement.value)
op = self.binop_map[type(statement.op)]
value = self.emit(ir.Binop(lhs, op, rhs, "augassign", var.ty))
self.emit(ir.Store(value, var.value))
else: # pragma: no cover
self.not_impl(statement)
示例8: visit_Name
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def visit_Name(self, node):
var = node.scopes.find(get_id(node))
if not var: #TODO why no scopes found for node id?
return get_id(node)
# if isinstance(var, object):
# return "o_b_j_e_c_t"
if isinstance(var.assigned_from, ast.For):
it = var.assigned_from.iter
return "std::declval<typename decltype({0})::value_type>()".format(
self.visit(it))
elif isinstance(var.assigned_from, ast.FunctionDef):
return get_id(var)
else:
return self.visit(var.assigned_from.value)
示例9: get_variables_from_node
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def get_variables_from_node(node: ast.AST) -> List[str]:
"""
Gets the assigned names from the list of nodes.
Can be used with any nodes that operate with ``ast.Name`` or ``ast.Tuple``
as targets for the assignment.
Can be used with nodes like ``ast.Assign``, ``ast.Tuple``, ``ast.For``,
``ast.With``, etc.
"""
names: List[str] = []
naive_attempt = extract_name(node)
if naive_attempt:
names.append(naive_attempt)
elif isinstance(node, ast.Tuple):
for subnode in node.elts:
extracted_name = get_variables_from_node(subnode)
if extracted_name:
names.extend(extracted_name)
return names
示例10: get_iter_vars_from_for_loops
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def get_iter_vars_from_for_loops(tree):
for_nodes = get_nodes_of_type(tree, (ast.For, ast.comprehension))
try:
iter_var_names = {n.target.id for n in for_nodes}
except AttributeError:
iter_var_names = {}
return iter_var_names
示例11: addBinding
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if existing and not self.differentForks(node, existing.source):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(ast.For, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
示例12: handleNodeStore
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (ast.For, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
示例13: for_stmt_rewrite
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def for_stmt_rewrite(target, iter, body, orelse, is_async=False):
orelse = orelse or []
as_store(target)
ty = ast.AsyncFor if is_async else ast.For
return ty(target, iter, body, orelse)
示例14: test_base_classes
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def test_base_classes(self):
self.assertTrue(issubclass(ast.For, ast.stmt))
self.assertTrue(issubclass(ast.Name, ast.expr))
self.assertTrue(issubclass(ast.stmt, ast.AST))
self.assertTrue(issubclass(ast.expr, ast.AST))
self.assertTrue(issubclass(ast.comprehension, ast.AST))
self.assertTrue(issubclass(ast.Gt, ast.AST))
示例15: visit_For
# 需要导入模块: import ast [as 别名]
# 或者: from ast import For [as 别名]
def visit_For(self, node: ast.For) -> None:
if (
not self._in_async_def and
len(node.body) == 1 and
isinstance(node.body[0], ast.Expr) and
isinstance(node.body[0].value, ast.Yield) and
node.body[0].value.value is not None and
targets_same(node.target, node.body[0].value.value) and
not node.orelse
):
offset = _ast_to_offset(node)
func_info = self._scope_stack[-1]
func_info.yield_from_fors.add(offset)
for target_node in ast.walk(node.target):
if (
isinstance(target_node, ast.Name) and
isinstance(target_node.ctx, ast.Store)
):
func_info.yield_from_names[target_node.id].add(offset)
# manually visit, but with target+body as a separate scope
self.visit(node.iter)
with self._scope():
self.visit(node.target)
for stmt in node.body:
self.visit(stmt)
assert not node.orelse
else:
self.generic_visit(node)