1. 程式人生 > 其它 >python獲取變數名

python獲取變數名

比如我們想有這麼一個函式,其用法是:pr(x),輸出是x = 3。我們需要從x得到'x'這個字串。
我寫了個很土的:
def whatis(x, verbose = 1):
    print(x, 'is a ', end=''); x = eval(x); print(type(x), end='')
    print(', which has ' + str(dir(x)) + '\n' if verbose else '')
whatis('[1]')
本來還能忍,但沒法對付函式引數:
def fn(x):
 whatis('x') # x在globals裡沒定義
 # global x2
x2 = x; whatis('x2') 土得掉渣。 上網搜了下,有老外說for name in globals(), eval()... x = y = 1 name = None # 不加這句python不讓你for,因為name要進到globals()裡去 for name in globals(): # 再加上locals() if eval(name) == x: return name # x和y咋區分啊?老外也有瞎說的。 老外也有厲害的: from varname import nameof # pip install varname def fn(x): print
(nameof(x), '=', x) fn(3) 下載原始碼瞅了眼,core.py 19KB, helpers.py 6K, ignore.py 15K, utils.py 14K. 我猜要在語法樹裡找。目前滿足於用別人的,先把鉤子函式做完: user32 = CDLL("user32.dll"); kernel32 = CDLL("kernel32.dll") whatis('user32'); whatis('cast', 1)