[英]How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON?
[英]Can I use 'eval' to define a function in Python?
我想使用 eval 定義一個 Python 函數:
func_obj = eval('def foo(a, b): return a + b')
但它返回無效的語法錯誤? 我怎樣才能做到?
順便說一句,如何在 Python 中將函數 obj 轉換為字符串對象?
使用exec
。 eval
用於表達式而不是語句。
>>> exec 'def foo(a, b): return a + b'
>>> foo(1, 2)
3
來自函數對象的函數代碼:
def func():
""" I'm func """
return "Hello, World"
...
>>> import inspect
>>> print inspect.getsource(func)
def func():
""" I'm func """
return "Hello, World"
您可以將eval
與lambda
一起使用,例如:
func_obj = lambda a, b: eval('a + b')
def test_eval():
exec('def foo(a, b): return a + b')
foo(1, 2)
@niitsuma 此代碼將返回錯誤: NameError: name 'foo' is not defined
這是因為 foo 是在您執行它的其他范圍內定義的。 要修復它並使其在外部范圍內可見,您可以創建 foo 全局變量:
def test_eval():
exec('global foo\ndef foo(a, b): return a + b')
foo(1, 2)
我寫
def test_eval():
exec('def foo(a, b): return a + b')
foo(1, 2)
在mypackage/tests/test_mycode.py
使用適當的mypackage/setup.py
。 但是python setup.py test
導致NameError: name 'foo' is not defined
。
如何從字符串測試代碼?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.