本文整理汇总了Python中ast.ListComp方法的典型用法代码示例。如果您正苦于以下问题:Python ast.ListComp方法的具体用法?Python ast.ListComp怎么用?Python ast.ListComp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.ListComp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _visit_list_set_gen_comp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def _visit_list_set_gen_comp(self: 'ASTTagger', node: ast.ListComp):
new = self.symtable.enter_new()
new.entered.add('.0')
new_tagger = ASTTagger(new)
node.elt = new_tagger.visit(node.elt)
head, *tail = node.generators
head.iter = self.visit(head.iter)
head.target = new_tagger.visit(head.target)
if head.ifs:
head.ifs = [new_tagger.visit(each) for each in head.ifs]
if any(each.is_async for each in node.generators):
new.cts.add(ContextType.Coroutine)
node.generators = [head, *[new_tagger.visit(each) for each in tail]]
return Tag(node, new)
示例2: ast_names
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def ast_names(code):
"""Iterator that yields all the (ast) names in a Python expression.
:arg code: A string containing a Python expression.
"""
# Syntax that allows new name bindings to be introduced is tricky to
# handle here, so we just refuse to do so.
disallowed_ast_nodes = (ast.Lambda, ast.ListComp, ast.GeneratorExp)
if sys.version_info >= (2, 7):
disallowed_ast_nodes += (ast.DictComp, ast.SetComp)
for node in ast.walk(ast.parse(code)):
if isinstance(node, disallowed_ast_nodes):
raise PatsyError("Lambda, list/dict/set comprehension, generator "
"expression in patsy formula not currently supported.")
if isinstance(node, ast.Name):
yield node.id
示例3: visit_Call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_Call(self, node: ast.Call) -> None:
if (
isinstance(node.func, ast.Name) and
node.func.id == 'set' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], SET_TRANSFORM)
):
arg, = node.args
key = _ast_to_offset(node.func)
if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts:
self.set_empty_literals[key] = arg
else:
self.sets[key] = arg
elif (
isinstance(node.func, ast.Name) and
node.func.id == 'dict' and
len(node.args) == 1 and
not node.keywords and
isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and
isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and
len(node.args[0].elt.elts) == 2
):
self.dicts[_ast_to_offset(node.func)] = node.args[0]
self.generic_visit(node)
示例4: _should_instrument_as_expression
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def _should_instrument_as_expression(self, node):
return (
isinstance(node, _ast.expr)
and hasattr(node, "end_lineno")
and hasattr(node, "end_col_offset")
and not getattr(node, "incorrect_range", False)
and "ignore" not in node.tags
and (not hasattr(node, "ctx") or isinstance(node.ctx, ast.Load))
# TODO: repeatedly evaluated subexpressions of comprehensions
# can be supported (but it requires some redesign both in backend and GUI)
and "ListComp.elt" not in node.tags
and "SetComp.elt" not in node.tags
and "DictComp.key" not in node.tags
and "DictComp.value" not in node.tags
and "comprehension.if" not in node.tags
)
示例5: _get_offsets
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def _get_offsets(func_ast):
import ast
for arg in func_ast.args:
start_line, start_col = arg.lineno - 2, arg.col_offset - 1
# horrible hack for http://bugs.python.org/issue31241
if isinstance(arg, (ast.ListComp, ast.GeneratorExp)):
start_col -= 1
yield start_line, start_col
for kw in func_ast.keywords:
yield kw.value.lineno - 2, kw.value.col_offset - 2 - (len(kw.arg) if kw.arg else 0)
示例6: test_listcomp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def test_listcomp(self):
self._simple_comp(ast.ListComp)
示例7: visit_ListComp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_ListComp(self, node: ast.ListComp) -> None:
"""Represent the list comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=node)
示例8: visit_SetComp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_SetComp(self, node: ast.ListComp) -> None:
"""Represent the set comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=node)
示例9: _execute_comprehension
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any:
"""Compile the generator or comprehension from the node and execute the compiled code."""
args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())]
if platform.python_version_tuple() < ('3', ):
raise NotImplementedError("Python versions below not supported, got: {}".format(platform.python_version()))
if platform.python_version_tuple() < ('3', '8'):
func_def_node = ast.FunctionDef(
name="generator_expr",
args=ast.arguments(args=args, kwonlyargs=[], kw_defaults=[], defaults=[]),
decorator_list=[],
body=[ast.Return(node)])
module_node = ast.Module(body=[func_def_node])
else:
func_def_node = ast.FunctionDef(
name="generator_expr",
args=ast.arguments(args=args, posonlyargs=[], kwonlyargs=[], kw_defaults=[], defaults=[]),
decorator_list=[],
body=[ast.Return(node)])
module_node = ast.Module(body=[func_def_node], type_ignores=[])
ast.fix_missing_locations(module_node)
code = compile(source=module_node, filename='<ast>', mode='exec')
module_locals = {} # type: Dict[str, Any]
module_globals = {} # type: Dict[str, Any]
exec(code, module_globals, module_locals) # pylint: disable=exec-used
generator_expr_func = module_locals["generator_expr"]
return generator_expr_func(**self._name_to_value)
示例10: visit_ListComp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_ListComp(self, node: ast.ListComp) -> Any:
"""Compile the list comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
return result
示例11: p_atom_5
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def p_atom_5(p):
'''atom : LSQB listmaker RSQB'''
# 1 2 3
if isinstance(p[2], ast.ListComp):
p[0] = p[2]
p[0].alt = p[1][1]
else:
p[0] = ast.List(p[2], ast.Load(), rule=inspect.currentframe().f_code.co_name, **p[1][1])
示例12: p_listmaker_1
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def p_listmaker_1(p):
'''listmaker : test list_for'''
# 1 2
p[0] = ast.ListComp(p[1], p[2], rule=inspect.currentframe().f_code.co_name)
inherit_lineno(p[0], p[1])
示例13: visit_ListComp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_ListComp(self, node):
# type: (ast.ListComp) -> None
# 'listcomp' is the string literal used by python
# to creating the SymbolTable for the corresponding
# list comp function.
self._handle_comprehension(node, 'listcomp')
示例14: visit_ListComp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_ListComp(self, list_comp: ast.ListComp) -> VisitExprReturnT:
"""
Desugars a list comprehension into nested for-loops and if-statements before flattening.
For example, this expression::
l = [y for x in it if cond for y in x]
gets desugared into::
l = []
for x in it:
if cond:
for y in x:
l.append(y)
This statement block then gets flattened.
"""
result_id = self.next_symbol_id()
# First, desugar the comprehension into nested for-loops and if-statements.
# Iteratively wrap `body` in for-loops and if-statements.
body: ast.stmt = ast.Expr(clone_node(
parse_ast_expr(f"{result_id}.append()"),
args=[list_comp.elt]
))
for comp in reversed(list_comp.generators):
if comp.is_async: # type: ignore # Mypy doesn't recognize the `is_async` attribute of `comprehension`.
raise NodeNotSupportedError(comp, "Asynchronous comprehension not supported")
for if_test in reversed(comp.ifs):
body = ast.If(test=if_test, body=[body], orelse=[])
body = ast.For(target=comp.target, iter=comp.iter, body=[body], orelse=[])
# Now that we've gotten rid of the comprehension, flatten the resulting action.
define_list = parse_ast_stmt(f"{result_id} = []")
return load(result_id), [define_list] + self.visit_stmt(body)
示例15: visit_Assign
# 需要导入模块: import ast [as 别名]
# 或者: from ast import ListComp [as 别名]
def visit_Assign(self, node):
# shortcut for expansion of ROM in case statement
if isinstance(node.value, ast.Subscript) and \
isinstance(node.value.slice, ast.Index) and\
isinstance(node.value.value.obj, _Rom):
rom = node.value.value.obj.rom
# self.write("// synthesis parallel_case full_case")
# self.writeline()
self.write("case (")
self.visit(node.value.slice)
self.write(")")
self.indent()
for i, n in enumerate(rom):
self.writeline()
if i == len(rom) - 1:
self.write("default: ")
else:
self.write("%s: " % i)
self.visit(node.targets[0])
if self.isSigAss:
self.write(' <= ')
self.isSigAss = False
else:
self.write(' = ')
s = self.IntRepr(n)
self.write("%s;" % s)
self.dedent()
self.writeline()
self.write("endcase")
return
elif isinstance(node.value, ast.ListComp):
# skip list comprehension assigns for now
return
# default behavior
self.visit(node.targets[0])
if self.isSigAss:
self.write(' <= ')
self.isSigAss = False
else:
self.write(' = ')
self.visit(node.value)
self.write(';')