2

特定のアステロイド ノードのすべての子ノードを再帰的にウォークスルーするジェネレータ関数を作成しています。

以下の例でnodeは、 はアステロイドfunctiondefノードです。 node.getchildren()ノード内にサブノードを持つジェネレータを返します。

私の目標は、含まれているすべてのノードを生成することです。(サブノードでも)

def recursive_walk(node):
    try:
        for subnode in list(node.get_children()):
            # yield subnode
            print(subnode)
            recursive_walk(subnode)            

    except AttributeError:
        # yield node       
        print(node)

    except TypeError:
        # yield node  
        print(node)

ここで、yield ステートメントをコメントアウトした場合。print ステートメントの場合、目的の結果が得られますが、ノードを生成すると、目的の出力が得られません。

これを再現するには: - asroid をインストールします。

import astroid

node = astroid.extract_node('''
def test_function(something): #@
    """Test function for getting subnodes"""
    assign_line = "String"
    ctx = len(assign_line)
    if ctx > 0:
        if ctx == 1:
            return 1
        if ctx > 10:
            return "Ten"
    else:
        return 0
''')
4

2 に答える 2