Skip to content

Instantly share code, notes, and snippets.

@RJ722
Created June 1, 2017 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RJ722/2a44d688d424211d23f4373e1047b6cf to your computer and use it in GitHub Desktop.
Save RJ722/2a44d688d424211d23f4373e1047b6cf to your computer and use it in GitHub Desktop.
Source range acquisition from a given node
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