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


Python ast.iter_fields方法代码示例

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


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

示例1: ast_to_string

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def ast_to_string(ast_node, line_indent=''):
    next_line_indent = line_indent + '  '

    if isinstance(ast_node, ast.AST):
        return (ast_node.__class__.__name__
                + '('
                + ','.join('\n' + next_line_indent + field_name + ' = ' + ast_to_string(child_node, next_line_indent)
                           for field_name, child_node in ast.iter_fields(ast_node))
                + ')')
    elif isinstance(ast_node, list):
        return ('['
                + ','.join('\n' + next_line_indent + ast_to_string(child_node, next_line_indent)
                           for child_node in ast_node)
                + ']')
    else:
        return repr(ast_node) 
开发者ID:google,项目名称:tmppy,代码行数:18,代码来源:_ast_to_string.py

示例2: fields_same

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def fields_same(n1: ast.AST, n2: ast.AST) -> bool:
    for (a1, v1), (a2, v2) in zip(ast.iter_fields(n1), ast.iter_fields(n2)):
        # ignore ast attributes, they'll be covered by walk
        if a1 != a2:
            return False
        elif _all_isinstance((v1, v2), ast.AST):
            continue
        elif _all_isinstance((v1, v2), (list, tuple)):
            if len(v1) != len(v2):
                return False
            # ignore sequences which are all-ast, they'll be covered by walk
            elif _all_isinstance(v1, ast.AST) and _all_isinstance(v2, ast.AST):
                continue
            elif v1 != v2:
                return False
        elif v1 != v2:
            return False
    return True 
开发者ID:asottile,项目名称:pyupgrade,代码行数:20,代码来源:pyupgrade.py

示例3: generic_visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def generic_visit(self, node):
        """Drive the visitor."""
        for _, value in ast.iter_fields(node):
            if isinstance(value, list):
                max_idx = len(value) - 1
                for idx, item in enumerate(value):
                    if isinstance(item, ast.AST):
                        if idx < max_idx:
                            item._bandit_sibling = value[idx + 1]
                        else:
                            item._bandit_sibling = None
                        item._bandit_parent = node

                        if self.pre_visit(item):
                            self.visit(item)
                            self.generic_visit(item)
                            self.post_visit(item)

            elif isinstance(value, ast.AST):
                value._bandit_sibling = None
                value._bandit_parent = node
                if self.pre_visit(value):
                    self.visit(value)
                    self.generic_visit(value)
                    self.post_visit(value) 
开发者ID:PyCQA,项目名称:bandit,代码行数:27,代码来源:node_visitor.py

示例4: compare

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def compare(computed, expected):
    """
    Assert that two AST nodes are the same.
    """
    assert type(computed) == type(expected)

    if isinstance(computed, list):
        for cv, ev in zip_longest(computed, expected):
            compare(cv, ev)
        return

    if not isinstance(computed, AST):
        assert computed == expected
        return

    for (cn, cv), (en, ev) in zip_longest(*map(iter_fields,
                                               (computed, expected))):
        assert cn == en
        compare(cv, ev) 
开发者ID:llllllllll,项目名称:codetransformer,代码行数:21,代码来源:test_decompiler.py

示例5: test_iter_fields

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def test_iter_fields(self):
        node = ast.parse('foo()', mode='eval')
        d = dict(ast.iter_fields(node.body))
        self.assertEqual(d.pop('func').id, 'foo')

        #XXX: tests for equality between astlist and regular lists not
        #     working, breaking this test up into its components.
        #self.assertEqual(d, {'keywords': [], 'kwargs': None,
        #                     'args': [], 'starargs': None})
        assert len(d) == 4
        assert d['keywords'] is not None
        assert len(d['keywords']) == 0
        assert d['args'] is not None
        assert len(d['args']) == 0
        assert d['kwargs'] is None
        assert d['starargs'] is None 
开发者ID:ofermend,项目名称:medicare-demo,代码行数:18,代码来源:test_ast.py

示例6: dumpTree

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def dumpTree (self):
        utils.log (False, 'Dumping syntax tree for module: {}\n', self.sourcePath)

        def walk (name, value, tabLevel):
            self.treeFragments .append ('\n{0}{1}: {2} '.format (tabLevel * '\t', name, type (value).__name__ ))
            if isinstance (value, ast.AST):
                for field in ast.iter_fields (value):
                    walk (field [0], field [1], tabLevel + 1)
            elif isinstance (value, list):
                for element in value:
                    walk ('element', element, tabLevel + 1)
            else:
                self.treeFragments.append ('= {0}'.format (value))

        self.treeFragments = []
        walk ('file', self.parseTree, 0)
        self.textTree = ''.join (self.treeFragments) [1:]

        with utils.create (self.treePath) as treeFile:
            treeFile.write (self.textTree) 
开发者ID:QQuick,项目名称:Transcrypt,代码行数:22,代码来源:compiler.py

示例7: generic_visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def generic_visit(self, node: ast.AST) -> None:
        """Called if no explicit visitor function exists for a node."""
        for _field, value in ast.iter_fields(node):
            if self.should_type_check:
                break

            if isinstance(value, list):
                for item in value:
                    if self.should_type_check:
                        break
                    if isinstance(item, ast.AST):
                        self.visit(item)
            elif isinstance(value, ast.AST):
                self.visit(value)


# Generic mypy error 
开发者ID:ambv,项目名称:flake8-mypy,代码行数:19,代码来源:flake8_mypy.py

示例8: visit_Assign

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def visit_Assign(self, node):
        for key, val in ast.iter_fields(node):
            if key == 'targets':
                for subnode in val:
                    if type(subnode) is ast.Tuple:
                        for subsubnode in subnode.elts:
                            crawler = myextract()
                            crawler.visit(subsubnode)
                            self.targets[fix_assign.sub(r'\1', ".".join(reversed(crawler.stack)))] = 1
                    else:
                        crawler = myextract()
                        crawler.visit(subnode)
                        self.targets[fix_assign.sub(r'\1', ".".join(reversed(crawler.stack)))] = 1
        self.depth += 1
        #ast.NodeVisitor.generic_visit(self, node)
        self.generic_visit(node)
        self.depth -= 1 
开发者ID:jhpyle,项目名称:docassemble,代码行数:19,代码来源:astparser.py

示例9: parse

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def parse(self, path):
        schemas = None
        file = open(path, 'r')
        data = file.read()
        root = ast.parse(data)

        try:
            for node in ast.walk(root):
                if isinstance(node, ast.Assign):
                    if hasattr(node.targets[0], 'id') and node.targets[0].id in schema_names:
                        schema_name = node.targets[0].id
                        for name, val in ast.iter_fields(node):
                            if isinstance(val, ast.Dict):
                                if not schemas:
                                    schemas = {}
                                schemas[schema_name] = self.convert(val)
        except:
            schemas = None
        file.close()
        return schemas 
开发者ID:EricssonResearch,项目名称:calvin-base,代码行数:22,代码来源:calvinsys_doc.py

示例10: dump

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def dump(node, annotate_fields=True, include_attributes=False, indent='  '):
    """Return a formatted dump of the tree in *node*.

    This is mainly useful for debugging purposes.  The returned string will
    show the names and the values for fields.  This makes the code impossible
    to evaluate, so if evaluation is wanted *annotate_fields* must be set to
    False.  Attributes such as line numbers and column offsets are not dumped
    by default.  If this is wanted, *include_attributes* can be set to True.
    """
    def _format(node, level=0):
        if isinstance(node, AST):
            fields = [(a, _format(b, level + 1)) for a, b in iter_fields(node)]
            if include_attributes and node._attributes:
                fields.extend([(a, _format(getattr(node, a), level + 1))
                               for a in node._attributes])
            return ''.join([
                node.__class__.__name__,
                '(\n' + indent + indent * level if fields else '(',
                (',\n' + indent + indent * level).join(('%s=%s' % field for field in fields)
                          if annotate_fields else
                          (b for a, b in fields)),
                ')'])
        elif isinstance(node, list):
            lines = ['[']
            lines.extend((indent * (level + 2) + _format(x, level + 2) + ','
                         for x in node))
            if len(lines) > 1:
                lines.append(indent * (level + 1) + ']')
            else:
                lines[-1] += ']'
            return '\n'.join(lines)
        return repr(node)

    if not isinstance(node, AST):
        raise TypeError('expected AST, got %r' % node.__class__.__name__)
    return _format(node) 
开发者ID:alecthomas,项目名称:importmagic,代码行数:38,代码来源:util.py

示例11: test_iter_fields

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def test_iter_fields(self):
        node = ast.parse('foo()', mode='eval')
        d = dict(ast.iter_fields(node.body))
        self.assertEqual(d.pop('func').id, 'foo')
        self.assertEqual(d, {'keywords': [], 'kwargs': None,
                             'args': [], 'starargs': None}) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:test_ast.py

示例12: str_node

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def str_node(node):
	if isinstance(node, ast.AST):
		fields = [(name, str_node(val)) for name, val in ast.iter_fields(node) if name not in ('left', 'right')]
		rv = '%s(%s' % (node.__class__.__name__, ', '.join('%s=%s' % field for field in fields))
		return rv + ')'
	else:
		return repr(node) 
开发者ID:dhrone,项目名称:pydPiper,代码行数:9,代码来源:asttest.py

示例13: ast_visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def ast_visit(node, level=0):
	print('  ' * level + str_node(node))
	for field, value in ast.iter_fields(node):
		if isinstance(value, list):
			for item in value:
				if isinstance(item, ast.AST):
					ast_visit(item, level=level+1)
		elif isinstance(value, ast.AST):
			ast_visit(value, level=level+1) 
开发者ID:dhrone,项目名称:pydPiper,代码行数:11,代码来源:asttest.py

示例14: _check_node_fields

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def _check_node_fields(self, node):
        for field in [f for _, f in ast.iter_fields(node)]:
            self._check_node(field) 
开发者ID:scrapinghub,项目名称:spidermon,代码行数:5,代码来源:interpreter.py

示例15: generic_visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import iter_fields [as 别名]
def generic_visit(self, node, container=None):
        for field, value in ast.iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, ast.AST):
                        yield from self.visit(item, container)
            elif isinstance(value, ast.AST):
                yield from self.visit(value, container) 
开发者ID:sourcegraph,项目名称:python-langserver,代码行数:10,代码来源:symbols.py


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