當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。