Symbol Table in Python

前端 未结 4 1249
北恋
北恋 2020-12-10 04:09

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

I mean, Python makes a symbol table for each program before actually running it. So my question is how can I

4条回答
  •  佛祖请我去吃肉
    2020-12-10 04:41

    You will likely enjoy Eli Bendersky's write up on the topic here

    In CPython, you have the symtable module available to you.

    In part 2, Eli describes a method which walks the symbol table that is incredibly helpful:

    def describe_symtable(st, recursive=True, indent=0):
        def print_d(s, *args):
            prefix = ' ' * indent
            print(prefix + s, *args)
    
        assert isinstance(st, symtable.SymbolTable)
        print_d('Symtable: type=%s, id=%s, name=%s' % (
                    st.get_type(), st.get_id(), st.get_name()))
        print_d('  nested:', st.is_nested())
        print_d('  has children:', st.has_children())
        print_d('  identifiers:', list(st.get_identifiers()))
    
        if recursive:
            for child_st in st.get_children():
                describe_symtable(child_st, recursive, indent + 5)
    

提交回复
热议问题