Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use 'eval' to define a function 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?

like image 599
xunzhang Avatar asked Nov 02 '13 12:11

xunzhang


People also ask

Is eval a function 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.

Why we should not use eval in Python?

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.

What is the difference between eval () and INT () function?

eval evaluates any python code. int tries to convert any type to integer (float, bool, string ...). you got it.


3 Answers

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"
like image 194
Ashwini Chaudhary Avatar answered Sep 29 '22 19:09

Ashwini Chaudhary


You can use eval with lambda, like:

func_obj = lambda a, b: eval('a + b')
like image 38
Saullo G. P. Castro Avatar answered Sep 29 '22 19:09

Saullo G. P. Castro


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)
like image 26
Maciek Avatar answered Sep 29 '22 19:09

Maciek