23

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?

vaultah
  • 44,105
  • 12
  • 114
  • 143
xunzhang
  • 2,838
  • 6
  • 27
  • 44
  • 1
    why do you need eval()? –  Nov 02 '13 at 13:00
  • 1
    Does this answer your question? [How do I execute a string containing Python code in Python?](https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python) – Georgy Aug 03 '20 at 18:04

4 Answers4

26

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"
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • how can I convert a function object to string? – xunzhang Nov 02 '13 at 13:01
  • @xunzhang It is possible only if function is defined somewhere, use `inspect.getsource`. – Ashwini Chaudhary Nov 02 '13 at 13:06
  • see this question(http://stackoverflow.com/questions/19740380/how-to-invoke-clients-callback-at-server-end), that is what I really need~ – xunzhang Nov 02 '13 at 13:07
  • 1
    @xunzhang Please ask only one question at a time. – Ashwini Chaudhary Nov 02 '13 at 13:20
  • Downvoted as your answer does not include why this is a bad idea and should not be done - and in OPs case, as mentioned by his previous comment, probably all he needs is `getattr`. – l4mpi Nov 02 '13 at 13:31
  • @hcwhsa thanks for your answer. But I do not think half solving problem or not solving a real problem is good, at least for myself. – xunzhang Nov 03 '13 at 06:32
  • 1
    Upvoted because it is clear with good examples, and doesn’t bother with explaining why this is a bad thing because that is all over the internet, and we should assume intelligence on the part of readers of stackoverflow. – kd4ttc Jul 24 '20 at 18:07
6

You can use eval with lambda, like:

func_obj = lambda a, b: eval('a + b')
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
4
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)
Maciek
  • 463
  • 8
  • 22
0

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?

niitsuma
  • 117
  • 1
  • 4