对于由ast模块计算的lineno偏移量,我有些不理解。通常,当我得到某个ast对象的lineno时,它会给出遇到对象的第一行。
例如,在下面的例子中,foo的lin
st='def foo():\n print "hello"'
import ast
print ast.parse(st).body[0].lineno
print ast.parse(st).body[0].body[0].lineno函数foo将返回1,并返回hello打印输出的2。
但是,如果我解析多行docstring (ast.Expr),则lineno提供的是最后一行。
st='def foo():\n """\n Test\n """'
import ast
print ast.parse(st).body[0].lineno
print ast.parse(st).body[0].body[0].lineno结果仍然是函数的1行,但对于docstring则是4行。我原以为它是在线的2,因为这是docstring开始的时候。
我想我要问的是,是否有一种方法总是能得到所有包括ast.Expr在内的所有对象的第一个直线。
发布于 2016-12-14 02:58:46
AST的源位置有很多不尽如人意的地方,但是ASTTokens库提供了很多这些信息,它用更有用的位置信息对AST节点进行注释。在你的例子中:
import asttokens
st='def foo():\n """\n Test\n """'
atok = asttokens.ASTTokens(st, parse=True)
print atok.tree.body[0].first_token.start[0]
print atok.tree.body[0].body[0].first_token.start[0]按需要打印1和2。也许更有趣的是,
print atok.get_text_range(atok.tree.body[0])
print atok.get_text_range(atok.tree.body[0].body[0])打印与节点对应的源文本范围:(0,35)和(15,35)。
https://stackoverflow.com/questions/30470944
复制相似问题