Home > OS >  Python ast Libary - retreive value of Node inside a function call
Python ast Libary - retreive value of Node inside a function call

Time:09-16

Follow up question of here: Python ast Libary - how to retreive value of a specific node

I use the following code to retreive {'console_scripts': ['main=smamesdemo.run.main:main']}

import ast

code = '''extras_require={"dev": dev_reqs}
x = 3
entry_points={
    "console_scripts": ["main=smamesdemo.run.main:main"]
}'''

for node in ast.walk(ast.parse(code)):
    if isinstance(node, ast.Assign) and node.targets[0].id == 'entry_points':
        expr = ast.Expression(body=node.value)
        ast.fix_missing_locations(expr)
        entry_points = eval(compile(expr, filename='', mode='eval'))

This works fine, but this example had a reduced complexity.

My real life example is a Python Package where I want to retrieve this values:

As minimal as it can be it looks like this:

import ast

code = '''extras_require={"dev": dev_reqs}
if __name__ == "__main__":
    setup(
        entry_points={
        "console_scripts": ["main=smamesdemo.run.main:main"]
        }
    )
'''

for node in ast.walk(ast.parse(code)):
    if isinstance(node, ast.Assign) and node.targets[0].id == 'entry_points':
        expr = ast.Expression(body=node.value)
        ast.fix_missing_locations(expr)
        entry_points = eval(compile(expr, filename='', mode='eval'))

print(entry_points)

Wrapping a function call around this will make the ast.Assign node disappear?! From my understanding, I would just get one more Node, but this is not the case.

Why does this happen and how get I retreive the desired values inside such a structure?

CodePudding user response:

In this case the value of the desired dict comes from a keyword argument, so you should look for an ast.keyword node instead of an ast.Assign node:

for node in ast.walk(ast.parse(code)):
    if isinstance(node, ast.keyword) and node.arg == 'entry_points':
        expr = ast.Expression(body=node.value)
        ast.fix_missing_locations(expr)
        entry_points = eval(compile(expr, filename='', mode='eval'))

Demo: https://replit.com/@blhsing/VividDarlingPhysics

  • Related