python如何将变量名作为字符串输出

import inspect

def retrieve_name(var):
“”"
Gets the name of var. Does it from the out most frame inner-wards.
:param var: variable to get name from.
:return: string
“”"
for fi in reversed(inspect.stack()):
names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
if len(names) > 0:
return names[0]

作者:陽台上的瑪格麗特
链接:https://www.zhihu.com/question/42768955/answer/744986655
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(Python)