以字符串形式获取变量名 [英] Getting the name of a variable as a string

查看:52
本文介绍了以字符串形式获取变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该线程讨论了如何在 Python 中以字符串形式获取函数的名称:如何以字符串形式获取函数名称?

This thread discusses how to get the name of a function as a string in Python: How to get a function name as a string?

如何对变量执行相同操作?与函数相反,Python 变量没有 __name__ 属性.

How can I do the same for a variable? As opposed to functions, Python variables do not have the __name__ attribute.

换句话说,如果我有一个变量,例如:

In other words, if I have a variable such as:

foo = dict()
foo['bar'] = 2

我正在寻找一个函数/属性,例如retrieve_name() 为了从此列表中在 Pandas 中创建一个 DataFrame,其中列名由实际字典的名称给出:

I am looking for a function/attribute, e.g. retrieve_name() in order to create a DataFrame in Pandas from this list, where the column names are given by the names of the actual dictionaries:

# List of dictionaries for my DataFrame
list_of_dicts = [n_jobs, users, queues, priorities]
columns = [retrieve_name(d) for d in list_of_dicts] 

推荐答案

使用 python-varname 包,您可以轻松检索变量的名称

Using the python-varname package, you can easily retrieve the name of the variables

https://github.com/pwwang/python-varname

v0.6.0 开始,在您的情况下,您可以:

As of v0.6.0, in your case, you can do:

from varname.helpers import Wrapper

foo = Wrapper(dict())

# foo.name == 'foo'
# foo.value == {}
foo.value['bar'] = 2

对于列表理解部分,你可以这样做:

For list comprehension part, you can do:

n_jobs = Wrapper(<original_value>) 
users = Wrapper(<original_value>) 
queues = Wrapper(<original_value>) 
priorities = Wrapper(<original_value>) 

list_of_dicts = [n_jobs, users, queues, priorities]
columns = [d.name for d in list_of_dicts]
# ['n_jobs', 'users', 'queues', 'priorities']
# REMEMBER that you have to access the <original_value> by d.value

您也可以尝试直接检索变量名称:

You can also try to retrieve the variable name DIRECTLY:

from varname import nameof

foo = dict()

fooname = nameof(foo)
# fooname == 'foo'

请注意,这在这种情况下如您预期的那样工作:

Note that this is working in this case as you expected:

n_jobs = <original_value>
d = n_jobs

nameof(d) # will return d, instead of n_jobs
# nameof only works directly with the variable

我是这个包的作者.如果您有任何问题,请告诉我,或者您可以在 Github 上提交问题.

I am the author of this package. Please let me know if you have any questions or you can submit issues on Github.

这篇关于以字符串形式获取变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆