使用eval和exec,如何编写匿名函数?

时间:2013-10-27 05:16:33

标签: python-3.x

>>> 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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

问题不是很清楚,但这是你想要的例子吗?

>>> c=compile('''\
... def some_function(x):
...   return x+2
... print(some_function(5))
... ''','<string>','exec')
>>> exec(c)
7
>>> c=compile('7+2','<string>','eval')
>>> eval(c)
9