从函数中返回未知名称的函数
Returning a function of unknown name from within a function
code = "def foo(): return 'bar'"
def lol(code):
exec code
return foo
a = lol(code)
print a()
这可以正常工作,但是当我们不知道调用字符串中的函数时,问题就开始了。如果我能保证代码会很小,只有一个函数,我怎么能return那个函数?
我想到的一个解决方案是只需要调用函数 'foo' 等,所以我可以 return 那样,但感觉很难看。
想法?
您可以通过显式指定 exec
应该用于全局和本地执行上下文的字典来实现。之后用于本地的那个应该有一个函数对象的条目,可以在不知道它的名字的情况下返回它,因为它应该是字典中定义的唯一项目:
from textwrap import dedent
import types
def lol(code):
globals_ = {"__builtins__": None} # no built-ins for safety
locals_ = {}
exec(code, globals_, locals_)
if len(locals_) != 1:
raise ValueError("code didn't define exactly one item")
value = locals_.popitem()[1] # get value of the one item defined
if type(value) != types.FunctionType:
raise ValueError("code didn't define a function")
return value # return function object that was defined
my_code = dedent("""
def foo():
return 'bar'
""")
a = lol(my_code)
print(a())
code = "def foo(): return 'bar'"
def lol(code):
exec code
return foo
a = lol(code)
print a()
这可以正常工作,但是当我们不知道调用字符串中的函数时,问题就开始了。如果我能保证代码会很小,只有一个函数,我怎么能return那个函数?
我想到的一个解决方案是只需要调用函数 'foo' 等,所以我可以 return 那样,但感觉很难看。
想法?
您可以通过显式指定 exec
应该用于全局和本地执行上下文的字典来实现。之后用于本地的那个应该有一个函数对象的条目,可以在不知道它的名字的情况下返回它,因为它应该是字典中定义的唯一项目:
from textwrap import dedent
import types
def lol(code):
globals_ = {"__builtins__": None} # no built-ins for safety
locals_ = {}
exec(code, globals_, locals_)
if len(locals_) != 1:
raise ValueError("code didn't define exactly one item")
value = locals_.popitem()[1] # get value of the one item defined
if type(value) != types.FunctionType:
raise ValueError("code didn't define a function")
return value # return function object that was defined
my_code = dedent("""
def foo():
return 'bar'
""")
a = lol(my_code)
print(a())