简体   繁体   English

我可以使用“eval”在 Python 中定义函数吗?

[英]Can I use 'eval' to define a function in Python?

I want to define a Python function using eval:我想使用 eval 定义一个 Python 函数:

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?顺便说一句,如何在 Python 中将函数 obj 转换为字符串对象?

Use exec .使用exec eval is used for expressions not statements. eval用于表达式而不是语句。

>>> 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 @niitsuma 此代码将返回错误: NameError: name 'foo' is not defined

This is because foo is defined in other scope that you execute it.这是因为 foo 是在您执行它的其他范围内定义的。 To fix it and make it visible in oouter scope, you can make foo global variable:要修复它并使其在外部范围内可见,您可以创建 foo 全局变量:

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 .mypackage/tests/test_mycode.py使用适当的mypackage/setup.py But python setup.py test cause NameError: name 'foo' is not defined .但是python setup.py test导致NameError: name 'foo' is not defined

How to test codes from string?如何从字符串测试代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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