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?
The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function.
Since the eval() function will evaluate any Python expressions, the hacker can easily get a list of files and folders on the server. To be honest, you probably will be fired if the above string is really evaluated by the eval() function.
eval evaluates any python code. int tries to convert any type to integer (float, bool, string ...). you got it.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With