當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.ListComp方法代碼示例

本文整理匯總了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) 
開發者ID:Xython,項目名稱:YAPyPy,代碼行數:18,代碼來源:symbol_analyzer.py

示例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 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:19,代碼來源:eval.py

示例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) 
開發者ID:asottile,項目名稱:pyupgrade,代碼行數:27,代碼來源:pyupgrade.py

示例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
        ) 
開發者ID:thonny,項目名稱:thonny,代碼行數:18,代碼來源:backend.py

示例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) 
開發者ID:samuelcolvin,項目名稱:python-devtools,代碼行數:14,代碼來源:debug.py

示例6: test_listcomp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import ListComp [as 別名]
def test_listcomp(self):
        self._simple_comp(ast.ListComp) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:4,代碼來源:test_ast.py

示例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) 
開發者ID:Parquery,項目名稱:icontract,代碼行數:11,代碼來源:_represent.py

示例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) 
開發者ID:Parquery,項目名稱:icontract,代碼行數:11,代碼來源:_represent.py

示例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) 
開發者ID:Parquery,項目名稱:icontract,代碼行數:37,代碼來源:_recompute.py

示例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 
開發者ID:Parquery,項目名稱:icontract,代碼行數:11,代碼來源:_recompute.py

示例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]) 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:10,代碼來源:hgawk_grammar.py

示例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]) 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:7,代碼來源:hgawk_grammar.py

示例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') 
開發者ID:aws,項目名稱:chalice,代碼行數:8,代碼來源:analyzer.py

示例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) 
開發者ID:NetSys,項目名稱:kappa,代碼行數:41,代碼來源:flatten.py

示例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(';') 
開發者ID:myhdl,項目名稱:myhdl,代碼行數:44,代碼來源:_toVerilog.py


注:本文中的ast.ListComp方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。