PythonソースコードのSymbol-Tableをどのように見ることができますか?
つまり、Pythonは、実際に実行する前に、各プログラムのシンボルテーブルを作成します。だから私の質問は、どうすればそのシンボルテーブルを出力として取得できるかということです。
PythonソースコードのSymbol-Tableをどのように見ることができますか?
つまり、Pythonは、実際に実行する前に、各プログラムのシンボルテーブルを作成します。だから私の質問は、どうすればそのシンボルテーブルを出力として取得できるかということです。
Pythonは、本質的に静的ではなく動的です。コンパイルされたオブジェクトコードのようなシンボルテーブルではなく、仮想マシンには変数のアドレス可能な名前空間があります。
dir()
or関数は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']
バイトコードを生成するときに使用されるシンボルテーブルについて質問する場合は、symtable
モジュールを確認してください。また、Eli Benderskyによるこれらの2つの記事は魅力的で、非常に詳細です。
パート2では、symtableの説明を出力できる関数について詳しく説明していますが、Python3用に作成されているようです。Python2.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は、プログラムが実行される前にシンボルテーブルを作成しません。実際、タイプと関数は実行中に定義できます(通常は定義されます)。
なぜPythonコードをコンパイルするのかを読むことに興味があるかもしれません。
@wberryによる詳細な回答も参照してください
ここでのトピックに関するEliBenderskyの記事をお楽しみいただけます。
CPythonでは、symtable
モジュールを利用できます。
パート2で、Eliは、非常に役立つシンボルテーブルをウォークする方法について説明します。
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)