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?
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"
You can use eval
with lambda
, like:
func_obj = lambda a, b: eval('a + b')
def test_eval():
exec('def foo(a, b): return a + b')
foo(1, 2)
@niitsuma This code will return error: NameError: name 'foo' is not defined
This is because foo is defined in other scope that you execute it. To fix it and make it visible in oouter scope, you can make foo global variable:
def test_eval():
exec('global foo\ndef foo(a, b): return a + b')
foo(1, 2)
I wrote
def test_eval():
exec('def foo(a, b): return a + b')
foo(1, 2)
in mypackage/tests/test_mycode.py
with approprite mypackage/setup.py
.
But python setup.py test
cause
NameError: name 'foo' is not defined
.
How to test codes from string?