带nod的Python ast col\u偏移

2024-03-29 09:33:17 发布

您现在位置:Python中文网/ 问答频道 /正文

ast.With节点在python2中有奇怪的col_offset值-它提供封闭表达式的偏移量,而不是with语句偏移量。你知道吗

它是一个bug还是一个特性?在py2/py3中是否还有其他节点具有相同的行为?你知道吗

import ast


def node_offset(src):
    node = ast.parse(src).body[0]
    print(node.col_offset, node.__class__.__name__)


node_offset('print(1)')
node_offset('raise  fd')
node_offset('with  exp: return 1')

py2输出:

(0, 'Print')
(0, 'Raise')
(6, 'With') <- offset of the 'exp'

py3输出:

0 'Print'
0 'Raise'
0 'With' <- looks correct to me

Tags: srcnode节点withpy3colastoffset