python獲取變量名


補充: print(f"{x= }"); 我又土了。
比如我們想有這么一個函數,其用法是: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)

咳,他那個也不好用:
x is a <class 'ctypes.CDLL'>, which has ['_FuncPtr', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_func_flags_', '_func_restype_', '_handle', '_name']

x is a <class 'function'>, which has ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM