body内でステートメントを使用することはできません。lambda
そのため、そのエラーが発生し、lambda
式のみが必要です。
しかし、Python 3exec
では関数であり、そこで正常に動作します。
>>> t = lambda x: exec(x)
>>> t("print('hello')")
hello
compile()
Python 2 では、次のように使用できますeval()
。
>>> t = lambda x: eval(compile(x, 'None','single'))
>>> strs = "print 'hello'"
>>> t(strs)
hello
ヘルプcompile()
:
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 the exec statement 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.