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


Python ast.SetComp方法代碼示例

本文整理匯總了Python中ast.SetComp方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.SetComp方法的具體用法?Python ast.SetComp怎麽用?Python ast.SetComp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.SetComp方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: ast_names

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [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

示例2: _should_instrument_as_expression

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [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

示例3: test_setcomp

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

示例4: _execute_comprehension

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [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

示例5: visit_SetComp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [as 別名]
def visit_SetComp(self, node: ast.SetComp) -> Any:
        """Compile the set 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

示例6: p_atom_7

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [as 別名]
def p_atom_7(p):
    '''atom : LBRACE dictorsetmaker RBRACE'''
    #              1              2      3
    if isinstance(p[2], (ast.SetComp, ast.DictComp)):
        p[0] = p[2]
        p[0].alt = p[1][1]
    else:
        keys, values = p[2]
        if keys is None:
            p[0] = ast.Set(values, rule=inspect.currentframe().f_code.co_name, **p[1][1])
        else:
            p[0] = ast.Dict(keys, values, rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:14,代碼來源:hgawk_grammar.py

示例7: p_dictorsetmaker_6

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [as 別名]
def p_dictorsetmaker_6(p):
    '''dictorsetmaker : test comp_for'''
    #                      1        2
    p[0] = ast.SetComp(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

示例8: _process_args

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [as 別名]
def _process_args(self, func_ast, code_lines, args, kwargs) -> 'Generator[DebugArgument, None, None]':  # noqa: C901
        import ast

        complex_nodes = (
            ast.Call,
            ast.Attribute,
            ast.Subscript,
            ast.IfExp,
            ast.BoolOp,
            ast.BinOp,
            ast.Compare,
            ast.DictComp,
            ast.ListComp,
            ast.SetComp,
            ast.GeneratorExp,
        )

        arg_offsets = list(self._get_offsets(func_ast))
        for i, arg in enumerate(args):
            try:
                ast_node = func_ast.args[i]
            except IndexError:  # pragma: no cover
                # happens when code has been commented out and there are fewer func_ast args than real args
                yield self.output_class.arg_class(arg)
                continue

            if isinstance(ast_node, ast.Name):
                yield self.output_class.arg_class(arg, name=ast_node.id)
            elif isinstance(ast_node, complex_nodes):
                # TODO replace this hack with astor when it get's round to a new release
                start_line, start_col = arg_offsets[i]

                if i + 1 < len(arg_offsets):
                    end_line, end_col = arg_offsets[i + 1]
                else:
                    end_line, end_col = len(code_lines) - 1, None

                name_lines = []
                for l_ in range(start_line, end_line + 1):
                    start_ = start_col if l_ == start_line else 0
                    end_ = end_col if l_ == end_line else None
                    name_lines.append(code_lines[l_][start_:end_].strip(' '))
                yield self.output_class.arg_class(arg, name=' '.join(name_lines).strip(' ,'))
            else:
                yield self.output_class.arg_class(arg)

        kw_arg_names = {}
        for kw in func_ast.keywords:
            if isinstance(kw.value, ast.Name):
                kw_arg_names[kw.arg] = kw.value.id
        for name, value in kwargs.items():
            yield self.output_class.arg_class(value, name=name, variable=kw_arg_names.get(name)) 
開發者ID:samuelcolvin,項目名稱:python-devtools,代碼行數:54,代碼來源:debug.py

示例9: loops

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import SetComp [as 別名]
def loops(node):
    # type: (ast.AST) -> Tuple[Loop, ...]
    """
    Return all the 'enclosing loops' of a node, up to the innermost class or
    function definition. This also includes the 'for in' clauses in list/dict/set/generator
    comprehensions. So for example, in this code:

      for x in ...:
          def foo():
              while True:
                  print([z for y in ...])

    The loops enclosing the node 'z' are 'while True' and 'for y in ...', in that order.
    """
    result = []
    while True:
        try:
            parent = node.parent
        except AttributeError:
            break
        if isinstance(parent, ast.FunctionDef):
            break

        is_containing_loop = (((isinstance(parent, ast.For) and parent.iter is not node or
                                isinstance(parent, ast.While))
                               and node not in parent.orelse) or
                              (isinstance(parent, ast.comprehension) and node in parent.ifs))
        if is_containing_loop:
            result.append(parent)

        elif isinstance(parent, (ast.ListComp,
                                 ast.GeneratorExp,
                                 ast.DictComp,
                                 ast.SetComp)):
            generators = parent.generators
            if node in generators:
                generators = list(takewhile(lambda n: n != node, generators))
            result.extend(reversed(generators))

        node = parent

    result.reverse()
    return tuple(result) 
開發者ID:alexmojaki,項目名稱:executing,代碼行數:45,代碼來源:tracer.py


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