![](/img/trans.png)
[英]What is the difference between locals and globals when using Python's eval()?
[英]Python's eval() and globals()
我正在嘗試使用eval()執行許多函數,我需要為它們創建一些運行環境。 在文檔中可以說你可以將全局變量作為第二個參數傳遞給eval()。
但似乎在我的情況下不起作用。 這是簡單的例子(我嘗試了兩種方法,聲明變量global和使用globals(),兩者都不起作用):
import test
global test_variable
test_variable = 'test_value'
g = globals()
g['test_variable'] = 'test_value'
eval('test.my_func()', g)
def my_func():
global test_variable
print repr(test_variable)
我得到了:
NameError:未定義全局名稱“test_variable”。
我應該怎么做才能將test_variable
傳遞給my_func()
? 假設我無法將其作為參數傳遞。
test_variable在test.py中應該是全局的。 你得到一個名稱錯誤,因為你試圖聲明一個尚不存在的變量全局。
所以你的my_test.py文件應該是這樣的:
test_variable = None
def my_func():
print test_variable
並從命令提示符運行:
>>> import my_test
>>> eval('my_test.my_func()')
None
>>> my_test.test_variable = 'hello'
>>> my_test.test_variable
'hello'
>>> eval('my_test.my_func()')
hello
通常使用eval()和全局變量是不好的形式,因此請確保您知道自己在做什么。
如果我錯了,請糾正我的Python專家。 我也在學習Python。 以下是我目前對為什么拋出NameError
異常的理解。
在Python中,您無法創建可以跨模塊訪問的變量而無需指定模塊名稱(即,在模塊mod1
訪問全局變量test
,您需要在模塊mod2
使用mod1.test
)。 全局變量的范圍幾乎僅限於模塊本身。
因此,當你在test.py
有以下內容時:
def my_func():
global test_variable
print repr(test_variable)
這里的test_variable
是指test.test_variable
(即test
模塊命名空間中的test_variable
)。
所以設置test_variable
在script.py
將放在變量__main__
命名空間( __main__
,因為這是你提供給Python解釋器來執行頂層模塊/腳本)。 因此,此test_variable
將位於不同的命名空間中,而不是在需要它的test
模塊命名空間中。 因此,Python生成一個NameError
因為它在搜索test
模塊全局命名空間和內置命名空間后無法找到變量(由於global
語句而跳過了本地函數命名空間)。
因此, test_variable
eval
工作,您需要在script.py
中的test
module命名空間中設置test_variable
:
import test
test.test_variable = 'test_value'
eval('test.my_func()')
有關Python范圍和命名空間的更多詳細信息,請參閱: http : //docs.python.org/tutorial/classes.html#python-scopes-and-name-spaces
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.