简体   繁体   中英

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?

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"

您可以将evallambda一起使用,例如:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM