data extraction from AST python file

Viewed 141

    code = """selection = ExtraTreesRegressor()
    selection.fit(X,y)"""
    
    ext = ast.parse(code)
    
    dump = ast.dump(ext)

After running the above lines of code I am getting the output below.


    Module(body=[Assign(targets=[Name(id='selection', ctx=Store())], value=Call(func=Name(id='ExtraTreesRegressor', ctx=Load()), args=[], keywords=[]), type_comment=None), Expr(value=Call(func=Attribute(value=Name(id='selection', ctx=Load()), attr='fit', ctx=Load()), args=[Name(id='X', ctx=Load()), Name(id='y', ctx=Load())], keywords=[]))], type_ignores=[])

I would like to get some details from the Assign node for example

I want to get details of ** ExtraTreesRegressor, fit, (X,y)** like below.

the output should be like this.

output:


    Class = [ExtraTreesRegressor]
    function_name = [fit]
    parameters = [X,y]

I am trying like this:


    Class = []
    function_name = []
    parameters = []
    
    if isinstance(no, ast.Assign):
        if isinstance(no.value, ast.Tuple) or isinstance(no.value, ast.List):
            for elts in no.value.elts:
                if hasattr(element, "id"):
                    # Check if var is in current context or not and add it if not
                    if element.id not in list_vars:
                        Class.append(element.id)
            

could you please help me with this?

0 Answers
Related