codeop --- Pythonコードをコンパイルする¶
ソースコード: Lib/codeop.py
codeop モジュールは、 code モジュールで行われているようなPythonの read-eval-printループをエミュレートするユーティリティを提供します。そのため、このモジュールを直接利用する場面はあまり無いでしょう。プログラムにこのようなループを含めたい場合は、 code モジュールの方が便利です。
この仕事には二つの部分があります:
Being able to tell if a line of input completes a Python statement: in short, telling whether to print '
>>>' or '...' next.Remembering which future statements the user has entered, so subsequent input can be compiled with these in effect.
codeop モジュールはこうしたことのそれぞれを行う方法とそれら両方を行う方法を提供します。
前者は実行するには:
-
codeop.compile_command(source, filename='<input>', symbol='single')¶ Tries to compile source, which should be a string of Python code and return a code object if source is valid Python code. In that case, the filename attribute of the code object will be filename, which defaults to
'<input>'. ReturnsNoneif source is not valid Python code, but is a prefix of valid Python code.source に問題がある場合は、例外を発生させます。無効なPython構文がある場合は、
SyntaxErrorを発生させます。また、無効なリテラルがある場合は、OverflowErrorまたはValueErrorを発生させます。The symbol argument determines whether source is compiled as a statement (
'single', the default), as a sequence of statement ('exec') or as an expression ('eval'). Any other value will causeValueErrorto be raised.注釈
ソースの終わりに達する前に、成功した結果をもってパーサは構文解析を止めることがあります。このような場合、後ろに続く記号はエラーとならずに無視されます。例えば、バックスラッシュの後ろに改行が2つあって、その後ろにゴミがあるかもしれません。パーサのAPIがより良くなればすぐに、この挙動は修正されるでしょう。
-
class
codeop.Compile¶ このクラスのインスタンスは組み込み関数
compile()とシグネチャが一致する__call__()メソッドを持っていますが、インスタンスが__future__文を含むプログラムテキストをコンパイルする場合は、インスタンスは有効なその文とともに続くすべてのプログラムテキストを'覚えていて'コンパイルするという違いがあります。
-
class
codeop.CommandCompiler¶ Instances of this class have
__call__()methods identical in signature tocompile_command(); the difference is that if the instance compiles program text containing a__future__statement, the instance 'remembers' and compiles all subsequent program texts with the statement in force.