I want to define a Python function using eval:
func_obj = eval('def foo(a, b): return a + b')
But it return invalid syntax error?
How can I make it?
Btw, how can I transform a function obj to a string object in Python?
解决方案
Use exec. eval is used for expressions not statements.
>>> exec 'def foo(a, b): return a + b'
>>> foo(1, 2)
3
Function code from function object:
def func():
""" I'm func """
return "Hello, World"
...
>>> import inspect
>>> print inspect.getsource(func)
def func():
""" I'm func """
return "Hello, World"