这是一种方法。我不会推荐任何重要的东西,因为它会很脆。但这是可以完成的。
创建一个使用inspect模块查找调用它的源代码的函数。然后,您可以解析源代码以标识要检索的变量名称。例如,这是一个名为的函数autodict,该函数获取变量列表并返回将变量名称映射为其值的字典。例如:
x = 'foo'
y = 'bar'
d = autodict(x, y)
print d
将给出:
{'x': 'foo', 'y': 'bar'}
检查源代码本身比搜索locals()or 更好,globals()因为后一种方法不会告诉您哪个变量是您想要的变量。
无论如何,这是代码:
def autodict(*args):
get_rid_of = ['autodict(', ',', ')', '\n']
calling_code = inspect.getouterframes(inspect.currentframe())[1][4][0]
calling_code = calling_code[calling_code.index('autodict'):]
for garbage in get_rid_of:
calling_code = calling_code.replace(garbage, '')
var_names, var_values = calling_code.split(), args
dyn_dict = {var_name: var_value for var_name, var_value in
zip(var_names, var_values)}
return dyn_dict
该操作在的行中进行inspect.getouterframes,该操作返回调用的代码中的字符串autodict。
这种魔术的明显缺点是,它对源代码的结构进行了假设。当然,如果它在解释器中运行,它将根本无法工作。
pip3 install python-varname==0.1.5;使用from varname import nameof