Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python ast Libary – retreive value of Node inside a function call

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading