Python.use(better, src=”PyPy”) #002: 関数 pycodegen.compile
|中級篇|
Python.use(better, src=”PyPy”) # ソースコードの歩き方《中級篇》
ソースコードの歩き方《PyPy1.2》
PyPy1.2 のリリースを機に、PyPy1.1 版を再構成したものです。
※ compiler の傘下にあるモジュールは、PyPy1.1.0 からの変更はありません。
関数 pycodegen.compile
関数 compile は、組み込み関数 compile に代わるものです。
$ cat compiler/pycodegen.py ... def compile(source, filename, mode, flags=None, dont_inherit=None): """Replacement for builtin compile() function""" if flags is not None or dont_inherit is not None: raise RuntimeError, "not implemented yet" if mode == "single": gen = Interactive(source, filename) elif mode == "exec": gen = Module(source, filename) elif mode == "eval": gen = Expression(source, filename) else: raise ValueError("compile() 3rd arg must be 'exec' or " "'eval' or 'single'") gen.compile() return gen.code
引数 mode には、次の中から
- single:単一の文(対話モード)
- exec:モジュール
- eval:任意の式
任意のモードを指定すると、ソースコード source を構文解析して、バイトコード gen.code に変換します。
■ 運命の分かれ道(Interactive/Module/Expression)
gen からリターン値を得る前に、メソッド呼び出し compile() をしているので、その謎を解明するには「副作用」を掘り起こす必要がありそうです。この先に続く道は、3つ Interactive/Module/Expression に分かれます。その中から、簡単な式 Expression を選んで、旅を続けましょう。
《TIPS》交通標識が複雑だと:ここで、ちょっと道草を…。次の条件式は、
if flags is not None or dont_inherit is not None:組み込み関数 any を利用すると、
if any((flags, dont_inherit)):簡潔で見通しが良くなります。しかも「情報隠蔽の原則」に沿って、手段 how(ルート:特定のオブジェクト None)に依存しないので、目的 what(ゴール)が明確になります。複雑な交通標識に目を奪われていると、思わぬ事故を招くものです。□
《NOTE》組み込み関数 exec:Python3.x では、組み込み関数 exec の第1引数に、このコードオブジェクトを指定できます。□
《HELP》組み込み関数 compile
Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) >>> help(compile) Help on built-in function compile in module builtins: compile(...) compile(source, filename, mode[, flags[, dont_inherit]]) -> code object Compile the source string (a Python module, statement or expression) into a code object that can be executed by exec() or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified.□
↑TOP
》作業中です《