Created
June 1, 2017 19:40
-
-
Save RJ722/2a44d688d424211d23f4373e1047b6cf to your computer and use it in GitHub Desktop.
Source range acquisition from a given node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
st='''import things\nclass foo:\n #There are comments\n print "hello" \n\ndef bla():\n a = 1\n b = 2\n c= a+b\n print c''' | |
import ast | |
tree = ast.parse(st) | |
for entry in tree.body: | |
if isinstance(entry, ast.FunctionDef): | |
lastBody = entry.body[-1] | |
while isinstance (lastBody,(ast.For,ast.While,ast.If)): | |
lastBody = lastBody.Body[-1] | |
lastLine = lastBody.lineno | |
print "Name: ",function.name | |
print "First Line: ",function.lineno | |
print "LastLine: ",lastLine | |
print "Source: " | |
if isinstance(st,str): | |
st = st.split("\n") | |
for i , line in enumerate(st,1): | |
if i in range(entry.lineno,lastLine+1): | |
print line | |
if isinstance(entry, ast.ClassDef): | |
lastBody = entry.body[-1] | |
while isinstance (lastBody,(ast.For,ast.While,ast.If)): | |
lastBody = lastBody.Body[-1] | |
lastLine = lastBody.lineno | |
print "Name: ",function.name | |
print "First Line: ",function.lineno | |
print "Last Line: ",lastLine | |
print "Source: " | |
if isinstance(st,str): | |
st = st.split("\n") | |
for i , line in enumerate(st,1): | |
if i in range(entry.lineno,lastLine+1): | |
print line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment