同一行代码的三种样子

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

print("hi") 这一行,分别看它的词数树的顶层节点类型编译产物里记下的名字

import ast, io, tokenize

LINE = 'print("hi")'
SRC2 = 'x = 1 + 2'

def toks(src):
    skip = (tokenize.NEWLINE, tokenize.NL, tokenize.ENDMARKER,
            tokenize.INDENT, tokenize.DEDENT)
    return [t.string for t in tokenize.generate_tokens(io.StringIO(src).readline)
            if t.type not in skip]

t = ast.parse(LINE)
code = compile(LINE, "<s>", "exec")
print(str(len(toks(LINE))) + "/" + type(t.body[0]).__name__
      + "/" + "/".join(code.co_names))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论