Following the docs here, and the answers in this answer and this, I have this code
source = r'C:\path\to\file\test.py'
with tokenize.open(source) as f:
readFile = f.read()
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
#print(type(node).__name__)
ast.NodeVisitor.generic_visit(self, node)
def visit_Assign(self, node):
try:
print("Assign :", node.value.id, node.lineno, node.col_offset)
except AttributeError:
print('Attribute Error:', node.lineno, node.col_offset)
ast.NodeVisitor.generic_visit(self, node)
node = ast.parse(file_contents)
v = Py2Neko()
v.visit(node)
For example, when I run it on this python file:
import os
def __init__(self, latitude, longitude, depth, magnitude):
self.latitude = latitude
self.longitude = longitude
self.depth = depth
self.magnitude = magnitude
def __str__(self):
depth = self.depth
if depth == -1:
depth = 'unknown'
magnitude = self.magnitude
if magnitude == -1:
depth = 'unknown'
I get this output:
Assign : latitude 9 1
Assign : longitude 10 1
Assign : depth 11 1
Assign : magnitude 12 1
Attribute Error: 16 1
Attribute Error: 18 2
Attribute Error: 20 1
Attribute Error: 22 2
I do not understand why (for example) on line 16 column 2 the depth = self.depth
raises an attribute error when I am attempting node.value.id
.
I am interested in being able to fetch that value id name for each of the assign statements, including cases like the above where where an attribute error occurs.