beniget
beniget copied to clipboard
Simple DefUse Analysis
Hi, I have been trying to perform a simple DefUse analysis on my code. Essentially, I just want to know for a given line of code, which other lines of code should be executed before it.
code = open("my_code.py", "r").read()
module = ast.parse(code)
duc = beniget.DefUseChains()
duc.visit(module)
From the example in the code, I know the duc
should contain the required information in the duc.chains
. But I am a little confused about the right way to access the information. For example, I know each line of code would be presented as a node in module
and I can access it by doing module.body[line #]
, how can I look it up in the duc.chains
? I have tried different ways and unfortunately no luck.
You shouldn't take a line a approach, but a node approach:
for d in duc.locals[module]:
print(d.name()) # prints the name of each defined identifier.
print(d.node) # the node that actually holds the definition. Generally an `ast.Name` or and `ast.FunctionDef`
print(d.users()) # the users of that definition
hope it helps?
Could I also ask here? I have a close task - I need to find all usages of definitions and return links between definition and uses on module level.
Until now, I've built DefUseChains, traversed each chain, found all chain ends and then with ancestors linked each start and end of the chain to the first ancestor. It seems that the solution that you provided solves the same problem but much easier, however I've run both solutions on the same piece of code and got different amount of these links. Am I missing something and which approach will be better for this problem?
Later today I will try to come up with a reproducible example.
@TitovS : the snippet above only finds top-level definition, while yours would also find inner definition, maybe that's the reason?
I suggest we close this issue.