>>> compile("""
def some_function(x):
return x+2
some_function""",'compiled function','single')
Traceback (most recent call last):
File "<pyshell#3>", line 4, in <module>
some_function""",'compiled function','single')
File "compiled function", line 4
some_function
^
SyntaxError: unexpected EOF while parsing
2 に答える
2
を使用して複数ステートメントの文字列をコンパイルする場合はcompile
、. また、コードをコンパイルした後、作成された関数にアクセスするために、コードを実行してグローバルをキャプチャする必要があります。single
exec
def anonymous(code):
# To fix the indentation
fixed_code = '\n'.join(line[4:] for line in code.splitlines())
_globals = {}
exec(compile(fixed_code, '<string>', 'exec'), _globals)
if 'f' not in _globals:
raise ValueError('You must name your function "f"')
return _globals['f']
anonymous('''
def f(x):
return x + 2
''')(12)
于 2013-10-27T05:33:59.273 に答える