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