Skip to content Skip to sidebar Skip to footer

Get Line Number Which Variable Is Defined In A Different File

is it possible for me to get the line number which variable is defined in a different file. for example: file1.py x = 5 mylist = [ 1, 2, 3] file2.py execfile('file1.py') # TODO

Solution 1:

A slightly improved version of Ashwini's answer, using the ast module and not regular expressions is:

import ast

classGetAssignments(ast.NodeVisitor):
    defvisit_Name(self, node):
        ifisinstance(node.ctx, ast.Store):
            print node.id, node.lineno

withopen('testing.py') as fin:
    module = ast.parse(fin.read())
    GetAssignments().visit(module)

And I think something similar can be used on already compiled objects...

Solution 2:

using regex:

try something like this, it will return all the lines wherever it finds x = something :

In [25]: withopen("fil.py") as f:
    print [index for index,line inenumerate(f) if re.findall(r'(x\s+=)',line)]
   ....:     
[0, 2, 3]

where fil.py contains:

x = 5mylist = [ 1, 2, 3]
x = 7x = 8

Post a Comment for "Get Line Number Which Variable Is Defined In A Different File"