Parse Python source for class / function line numbers

I want to analyze the Python file and for each line, find out the line number of the beginning of the function / method / class in which the statement is located.

An ideal return would be a dictionary with each line number as a key, and the value is the line number of the function / class / method to which the line of code belongs.

0: def(a):
1:     print 'hi mom'
2:     print 'hello world'

Return:

{1: 0
 2: 0}

I could not find valuable information on this issue. I am considering writing a kind of hacker solution that analyzes indentation levels and breaks into the dictionary I'm looking for.

+4
source share
1 answer

ast module, . , ast.parse() , AST. , node. AST.

+4

All Articles