AST python如何在不同文件中的方法之间查找连接

时间:2018-08-21 18:54:26

标签: python abstract-syntax-tree

我想索引整个应用程序中的所有方法以及它们之间的连接(最终是带有子目录和文件的目录)。我正在使用ast,将目录循环到各个文件,然后将它们加载到ast对象中,就像ast.parse(self.file_content)

我要创建的索引是这个 connection

这是我的代码(如果相关)。

def scan(self):
    '''
        scans a file line by line while keeping context of location and classes
        indexes a file buffer content into a ast, Abstract Syntax Trees, https://en.wikipedia.org/wiki/AST.
        Then, iterate over the elements, find relevant ones to index, and index them into the db.
    '''
    parsed_result = ast.parse(self.file_content)
    for element in parsed_result.body:
        results = self.index_element(element)


def index_element(self, element, class_name=None):
    '''

        if element is relevant, meaning method -> index
        if element is Class -> recursively call it self

    :param element:
    :param class_name:
    :return: [{insert_result: <db_insert_result>, 'structured_data': <method> object}, ...]
    '''
    # find classes
        # find methods inside classes
    # find hanging functions

    # validation on element type
    if self.should_index_element(element):
        if self.is_class_definition(element):
            class_element = element
            indexed_items = []
            for inner_element in class_element.body:
                # recursive call
                results = self.index_element(inner_element, class_name=class_element.name)
                indexed_items += results

            return indexed_items
        else:
            structured_data = self.structure_method_into_an_object(element, class_name=class_name)
            result_graph = self.dal_client.methods_graph.insert_or_update(structured_data)
            return "WhatEver"

    return "WhatEver"

我的问题是,是否可以使用ast创建该图。如果是,怎么办? 据我了解,由于无法一次将一个文件加载到ast对象,并且不知道外部方法,我目前无法这样做。

这是我要在它们之间链接的2个文件的示例:

sample_a.py

from sample_class_b import SampleClassB

sample_b = SampleClassB()

class SampleClassA(object):
    def __init__(self):
        self.a = 1

    def test_call_to_another_function(self):
        return sample_b.test()

sample_b.py

class SampleClassB(object):
    def __init__(self):
        self.b = 1

    def test(self):
        return True

0 个答案:

没有答案