当前位置: 首页>>代码示例>>Python>>正文


Python ast.iter_child_nodes方法代码示例

本文整理汇总了Python中ast.iter_child_nodes方法的典型用法代码示例。如果您正苦于以下问题:Python ast.iter_child_nodes方法的具体用法?Python ast.iter_child_nodes怎么用?Python ast.iter_child_nodes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.iter_child_nodes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _add_section

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def _add_section(self, node):
        """
        Register the current node as a new context block
        """
        self._filldown(node.lineno)

        # push a new context onto stack
        self.context.append(node.name)
        self._update_current_context()

        for _ in map(self.visit, iter_child_nodes(node)):
            pass

        # restore current context
        self.context.pop()
        self._update_current_context() 
开发者ID:ChrisBeaumont,项目名称:smother,代码行数:18,代码来源:python.py

示例2: get_config_comments

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def get_config_comments(func):
    filename = inspect.getfile(func)
    func_body, line_offset = get_function_body(func)
    body_source = dedent_function_body(func_body)
    body_code = compile(body_source, filename, "exec", ast.PyCF_ONLY_AST)
    body_lines = body_source.split("\n")

    variables = {"seed": "the random seed for this experiment"}

    for ast_root in body_code.body:
        for ast_entry in [ast_root] + list(ast.iter_child_nodes(ast_root)):
            if isinstance(ast_entry, ast.Assign):
                # we found an assignment statement
                # go through all targets of the assignment
                # usually a single entry, but can be more for statements like:
                # a = b = 5
                for t in ast_entry.targets:
                    add_doc(t, variables, body_lines)

    return variables 
开发者ID:IDSIA,项目名称:sacred,代码行数:22,代码来源:config_scope.py

示例3: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def __init__(self, *args, **kwargs):
        super(Source, self).__init__(*args, **kwargs)
        if self.tree and self.text:
            self.highlighted = ArgDefaultDict(
                lambda style: raw_highlight(self.text, style).splitlines()
            )
        else:
            self.lines = defaultdict(lambda: u'SOURCE IS UNAVAILABLE')
            self.highlighted = defaultdict(lambda: self.lines)
        self.statements = StatementsDict(self)
        self.nodes = []
        if self.tree:
            self.tree._depth = 0
            for node in ast.walk(self.tree):
                node._tree_index = len(self.nodes)
                self.nodes.append(node)
                for child in ast.iter_child_nodes(node):
                    child._depth = node._depth + 1 
开发者ID:alexmojaki,项目名称:snoop,代码行数:20,代码来源:formatting.py

示例4: walk

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def walk(node, stop_at=tuple(), ignore=tuple()):
    """Walk through the children of an ast node.

    Args:
        node: an ast node
        stop_at: stop traversing through these nodes, including the matching
            node
        ignore: stop traversing through these nodes, excluding the matching
            node

    Returns: a generator of ast nodes
    """
    todo = deque([node])
    while todo:
        node = todo.popleft()
        if isinstance(node, ignore):
            # dequeue next node
            continue
        if not isinstance(node, stop_at):
            next_nodes = ast.iter_child_nodes(node)
            for n in next_nodes:
                todo.extend([n])
        yield node 
开发者ID:kubeflow-kale,项目名称:kale,代码行数:25,代码来源:ast.py

示例5: iter_children_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def iter_children_ast(node):
  # Don't attempt to process children of JoinedStr nodes, which we can't fully handle yet.
  if is_joined_str(node):
    return

  if isinstance(node, ast.Dict):
    # override the iteration order: instead of <all keys>, <all values>,
    # yield keys and values in source order (key1, value1, key2, value2, ...)
    for (key, value) in zip(node.keys, node.values):
      if key is not None:
        yield key
      yield value
    return

  for child in ast.iter_child_nodes(node):
    # Skip singleton children; they don't reflect particular positions in the code and break the
    # assumptions about the tree consisting of distinct nodes. Note that collecting classes
    # beforehand and checking them in a set is faster than using isinstance each time.
    if child.__class__ not in SINGLETONS:
      yield child 
开发者ID:gristlabs,项目名称:asttokens,代码行数:22,代码来源:util.py

示例6: locate_loop_body

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def locate_loop_body(module, loop):
    ends = set([ node.lineno 
                    for node in ast.walk(module) 
                    if hasattr(node, 'lineno') and node.lineno > loop.lineno ])

    starts = set()

    def visit(node):
        if hasattr(node, 'lineno') and node.lineno > loop.lineno:
            starts.add(node.lineno)
            if node.lineno in ends:
                ends.remove(node.lineno)
        for child in ast.iter_child_nodes(node):
            visit(child)

    for stmt in loop.body:
        visit(stmt)

    if len(ends) == 0: 
        return min(starts), -1

    return min(starts), min(ends) 
开发者ID:julvo,项目名称:reloading,代码行数:24,代码来源:reloading.py

示例7: check_for_b012

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [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)) 
开发者ID:PyCQA,项目名称:flake8-bugbear,代码行数:18,代码来源:bugbear.py

示例8: diff

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def diff(a, b):
        assert a is not None
        assert b is not None

        def _str_dist(i, j):
            return 0 if i == j else 1

        def _get_label(n):
            return type(n).__name__

        def _get_children(n):
            if not hasattr(n, 'children'):
                n.children = list(ast.iter_child_nodes(n))
            return n.children

        import zss
        res = zss.distance(a.func_node, b.func_node, _get_children,
                           lambda node: 0,  # insert cost
                           lambda node: _str_dist(_get_label(node), ''),  # remove cost
                           lambda _a, _b: _str_dist(_get_label(_a), _get_label(_b)), )  # update cost
        return res 
开发者ID:fyrestone,项目名称:pycode_similar,代码行数:23,代码来源:pycode_similar.py

示例9: parse_flags

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def parse_flags(synth_py_path="synth.py") -> typing.Dict[str, typing.Any]:
    """Extracts flags from a synth.py file.

    Keyword Arguments:
        synth_py_path {str or Path} -- Path to synth.py (default: {"synth.py"})

    Returns:
        typing.Dict[str, typing.Any] -- A map of all possible flags.  Flags not
          found in synth.py will be set to their default value.
    """
    flags = copy.copy(_SYNTH_PY_FLAGS)
    path = pathlib.Path(synth_py_path)
    try:
        module = ast.parse(path.read_text())
    except SyntaxError:
        return flags  # Later attempt to execute synth.py will give a clearer error message.

    for child in ast.iter_child_nodes(module):
        if isinstance(child, ast.Assign):
            for target in child.targets:
                if isinstance(target, ast.Name) and target.id in flags:
                    flags[target.id] = ast.literal_eval(child.value)
    return flags 
开发者ID:googleapis,项目名称:synthtool,代码行数:25,代码来源:flags.py

示例10: get_version

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def get_version():
    module_path = os.path.join(
        os.path.dirname(__file__),
        'sqlalchemy_utc',
        'version.py')
    module_file = open(module_path)
    try:
        module_code = module_file.read()
    finally:
        module_file.close()
    tree = ast.parse(module_code, module_path)
    for node in ast.iter_child_nodes(tree):
        if not isinstance(node, ast.Assign) or len(node.targets) != 1:
            continue
        target, = node.targets
        if isinstance(target, ast.Name) and target.id == '__version__':
            return node.value.s 
开发者ID:spoqa,项目名称:sqlalchemy-utc,代码行数:19,代码来源:setup.py

示例11: get_accessed

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def get_accessed(node):
    '''Get names, but ignore variables names to the left hand side
    That is to say, in case of
       a = b + 1
    we consider b as "being accessed", while a is not.
    '''
    if isinstance(node, ast.Assign):
        return get_accessed(node.value)
    elif isinstance(node, ast.Name):
        return {node.id}
    names = set()
    if isinstance(node, list):
        for x in node:
            names |= get_accessed(x)
    else:
        for x in ast.iter_child_nodes(node):
            names |= get_accessed(x)
    return names 
开发者ID:vatlab,项目名称:sos,代码行数:20,代码来源:eval.py

示例12: _process_child_nodes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def _process_child_nodes(
    node: ast.AST,
    increment_by: int,
    complexity_calculator: Callable[[ast.AST, int], int],
) -> int:
    child_complexity = 0

    for node_num, child_node in enumerate(ast.iter_child_nodes(node)):
        if isinstance(node, ast.Try):
            if node_num == 1:
                increment_by += 1  # add +1 for all try nodes except body
            if node_num:
                child_complexity += max(1, increment_by)
        child_complexity += complexity_calculator(
            child_node,
            increment_by,
        )

    return child_complexity 
开发者ID:wemake-services,项目名称:wemake-python-styleguide,代码行数:21,代码来源:cognitive.py

示例13: _set_parent

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def _set_parent(tree: ast.AST) -> ast.AST:
    """
    Sets parents for all nodes that do not have this prop.

    This step is required due to how `flake8` works.
    It does not set the same properties as `ast` module.

    This function was the cause of `issue-112`. Twice.
    Since the ``0.6.1`` we use ``'wps_parent'`` with a prefix.
    This should fix the issue with conflicting plugins.

    .. versionchanged:: 0.0.11
    .. versionchanged:: 0.6.1

    """
    for statement in ast.walk(tree):
        for child in ast.iter_child_nodes(statement):
            setattr(child, 'wps_parent', statement)  # noqa: B010
    return tree 
开发者ID:wemake-services,项目名称:wemake-python-styleguide,代码行数:21,代码来源:ast_tree.py

示例14: visit_Compare

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def visit_Compare(self, node):
        node.signed = False
        # for n in ast.iter_child_nodes(node):
        for n in [node.left] + node.comparators:
            self.visit(n)
            if n.signed:
                node.signed = True 
开发者ID:myhdl,项目名称:myhdl,代码行数:9,代码来源:_toVerilog.py

示例15: generic_visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_child_nodes [as 别名]
def generic_visit(self, node):
        if hasattr(node, 'lineno'):
            self._filldown(node.lineno + 1)

        for _ in map(self.visit, iter_child_nodes(node)):
            pass 
开发者ID:ChrisBeaumont,项目名称:smother,代码行数:8,代码来源:python.py


注:本文中的ast.iter_child_nodes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。