Python中的符号表

Rah*_*pta 11 python symbol-table

我们怎样才能看到python源代码的符号表?

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

wbe*_*rry 9

Python本质上是动态的而不是静态的.虚拟机不是像编译对象代码中的符号表,而是具有变量的可寻址命名空间.

dir()dir(module)函数在代码中的那点返回有效的命名空间.它主要用于交互式解释器,但也可以由代码使用.它返回一个字符串列表,每个字符串都是一个带有某个值的变量.

globals()函数将变量名称的字典返回给变量值,其中变量名称在此时被视为全局范围.

locals()函数将变量名称字典返回到变量值,其中变量名称在此时被视为范围内的本地变量.

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import base64
>>> dir(base64)
['EMPTYSTRING', 'MAXBINSIZE', 'MAXLINESIZE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_b32alphabet', '_b32rev', '_b32tab', '_translate', '_translation', '_x', 'b16decode', 'b16encode', 'b32decode', 'b32encode', 'b64decode', 'b64encode', 'binascii', 'decode', 'decodestring', 'encode', 'encodestring', 'k', 're', 'standard_b64decode', 'standard_b64encode', 'struct', 'test', 'test1', 'urlsafe_b64decode', 'urlsafe_b64encode', 'v']
Run Code Online (Sandbox Code Playgroud)


voi*_*hos 6

如果您询问生成字节码时使用的符号表,请查看该symtable模块.此外,Eli Bendersky的这两篇文章很有趣,而且非常详细:

Python Internals:符号表,第1部分

Python Internals:符号表,第2部分

在第2部分中,他详细介绍了一个可以打印出symtable描述的函数,但它似乎是为Python 3编写的.这是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)
Run Code Online (Sandbox Code Playgroud)


Joh*_*erg 5

Python在程序执行之前不会生成符号表.实际上,类型和函数可以(并且通常)在执行期间定义.

您可能有兴趣阅读为什么要编译Python代码?

另请参阅@wberry的详细答案