jeudi 24 octobre 2019

How to work with python ast module to analyse if-statements

**I have to analyse python code that contains if statements and I found the ast module: https://docs.python.org/3.8/library/ast.html Somehow the documentation is not self-explanatory. I found an example here: https://www.mattlayman.com/blog/2018/decipher-python-ast/ that uses the ast.NodeVisitor helper class but I am struggeling how to adopt this example to get the details of an if statement.

#code to parse:
toggleSwitch = False

# check for someValue in the key-value store
if 'someValue' in context['someKey']:
    toggleSwitch = True
#code of the analyser:
class Analyzer(ast.NodeVisitor):
    def visit_If(self, node):
        print("If:",node.test.left)
        self.stats["if"].append(node.body)
        self.generic_visit(node)

I expect to access the 'someValue' element in some kind of attribute of the node inside the visit_If function, but I don't know how to do it exactly.**

Aucun commentaire:

Enregistrer un commentaire