26

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?

2

4 Answers 4

31

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"
Sign up to request clarification or add additional context in comments.

7 Comments

how can I convert a function object to string?
@xunzhang It is possible only if function is defined somewhere, use inspect.getsource.
see this question(stackoverflow.com/questions/19740380/…), that is what I really need~
@xunzhang Please ask only one question at a time.
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.
|
6

You can use eval with lambda, like:

func_obj = lambda a, b: eval('a + b')

1 Comment

def f(a,b) = return eval('a+b') does the same.
6
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)

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.