Python中的符号表 [英] Symbol Table in Python

查看:358
本文介绍了Python中的符号表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何看到python源代码的符号表?

How can we see the Symbol-Table of a python source code?

我的意思是,Python在实际运行每个程序之前会为其创建一个符号表.所以我的问题是如何获取该符号表作为输出?

I mean, Python makes a symbol table for each program before actually running it. So my question is how can I get that symbol-table as output?

推荐答案

如果您询问生成字节码时使用的符号表,请查看

If you are asking about the symbol table that is used when generating bytecode, take a look at the symtable module. Also, these two articles by Eli Bendersky are fascinating, and very detailed:

Python内部:符号表,一部分1

Python内部:符号表,一部分2

在第2部分中,他详细介绍了可以打印出symtable描述的函数,但是它似乎是为Python 3编写的.这是Python 2.x的版本:

In part 2, he details a function that can print out a description of a symtable, but it seems to have been written for Python 3. Here's a version for Python 2.x:

def describe_symtable(st, recursive=True, indent=0):
    def print_d(s, *args):
            prefix = ' ' *indent
            print prefix + s + ' ' + ' '.join(args)

    print_d('Symtable: type=%s, id=%s, name=%s' % (
            st.get_type(), st.get_id(), st.get_name()))
    print_d('  nested:', str(st.is_nested()))
    print_d('  has children:', str(st.has_children()))
    print_d('  identifiers:', str(list(st.get_identifiers())))

    if recursive:
            for child_st in st.get_children():
                    describe_symtable(child_st, recursive, indent + 5)

这篇关于Python中的符号表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆