根據Python文檔,dir()
(不含參數)和locals()
都會在一個名爲local scope
的東西中計算變量列表。第一個返回名稱列表,第二個返回名稱 - 值對的字典。這是唯一的區別嗎?這總是有效的嗎?Python中dir()和locals()之間的區別?
assert dir() == sorted(locals().keys())
根據Python文檔,dir()
(不含參數)和locals()
都會在一個名爲local scope
的東西中計算變量列表。第一個返回名稱列表,第二個返回名稱 - 值對的字典。這是唯一的區別嗎?這總是有效的嗎?Python中dir()和locals()之間的區別?
assert dir() == sorted(locals().keys())
的dir()
時不帶參數調用的輸出是locals()
幾乎相同,但dir()
返回一個字符串列表和locals()
返回一個字典,你可以更新字典來增加新的變數。
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
locals(...)
locals() -> dictionary
Update and return a dictionary containing the current scope's local variables.
類型:
>>> type(locals())
<type 'dict'>
>>> type(dir())
<type 'list'>
更新或添加使用locals()
新的變量:使用dir()
In [2]: locals()['a']=2
In [3]: a
Out[3]: 2
,但是,這並不工作:
In [7]: dir()[-2]
Out[7]: 'a'
In [8]: dir()[-2]=10
In [9]: dir()[-2]
Out[9]: 'a'
In [10]: a
Out[10]: 2
精確問題是「什麼功能,以用來檢查是否存在變量在本地範圍內定義」。
訪問Python中未定義的變量引發了一個異常:
>>> undefined
NameError: name 'undefined' is not defined
就像任何其他的異常,你可以捕捉它:
try:
might_exist
except NameError:
# Variable does not exist
else:
# Variable does exist
我需要知道的語言架構編寫更好的代碼。
這不會讓你的代碼更好。你應該從來沒有讓自己陷入需要這樣的事情的情況下,它幾乎總是錯誤的方法。
你試圖解決什麼問題?你爲什麼需要知道? – phant0m
我需要知道語言體系結構來編寫更好的代碼。確切的問題是'使用什麼函數來檢查某些變量是否在本地範圍內定義'。 – grigoryvp