0

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.

Community
  • 1
  • 1
  • Is the indentation of the code you've shown correct? I'm guessing the `visit_Assign` function is supposed to be a method of the `Py2Neko` class, but it's not currently indented to make it one. – Blckknght Jun 02 '16 at 09:26
  • Nice catch. My bad, corrected. Thanks –  Jun 02 '16 at 09:28
  • 1
    The issue you're running into is that the right side of the assignment is not always a simple name. It can be any kind of expression. In the code file you show, two of the assignments are doing attribute lookups (e.g. the `depth` attribute is looked up on the name `self`). Two more are assigning string literals. You could adapt your code for those specific kinds of values, but I suspect it will fail for some other kind of expression next. I'm not sure what the best solution is. Probably there's some way to turn the whole sub-tree into a string, but I don't know how (thus this being a comment). – Blckknght Jun 02 '16 at 09:39

0 Answers0