我已经读了如何获得一个函数名作为字符串?。

如何对变量做同样的事情呢?与函数相反,Python变量没有__name__属性。

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

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

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

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

当前回答

如果有两个值相同的变量,前面的一些情况会失败。所以提醒它很方便:

定义函数:

# Variable to string of variable name

def var_name(variable,i=0):

  results = []
  for name in globals():   
     if eval(name) == variable:
       results.append(name)

  if len(results) > 1:
    print('Warning:' )
    print('   var_name() has found',len(results), 'possible outcomes.')
    print('   Please choose the suitable parameter "i". Where "i" is the index')
    print('   that matches your choice from the list below.')
    print('  ',results) ; print('')

  return results[i]

Use:

var_1 = 10
var_name(var_1) # Output will be "var_1"

如果你有两个相同值的变量,比如var_1 = 8和var_2 = 8,那么就会出现一个警告。

var_1 = 8
var_2 = 8
var_name(var_2)  # Output will be "var_1" too but Warning will appear

其他回答

您可以尝试以下方法来检索您定义的函数的名称(但不适用于内置函数):

import re
def retrieve_name(func):
    return re.match("<function\s+(\w+)\s+at.*", str(func)).group(1)

def foo(x):
    return x**2

print(retrieve_name(foo))
# foo

你可以以kwargs的形式获取变量,并以字符串的形式返回:

var=2
def getVarName(**kwargs):
    return list(kwargs.keys())[0]

print (getVarName(var = var))

注:变量名必须等于自身。

如果有两个值相同的变量,前面的一些情况会失败。所以提醒它很方便:

定义函数:

# Variable to string of variable name

def var_name(variable,i=0):

  results = []
  for name in globals():   
     if eval(name) == variable:
       results.append(name)

  if len(results) > 1:
    print('Warning:' )
    print('   var_name() has found',len(results), 'possible outcomes.')
    print('   Please choose the suitable parameter "i". Where "i" is the index')
    print('   that matches your choice from the list below.')
    print('  ',results) ; print('')

  return results[i]

Use:

var_1 = 10
var_name(var_1) # Output will be "var_1"

如果你有两个相同值的变量,比如var_1 = 8和var_2 = 8,那么就会出现一个警告。

var_1 = 8
var_2 = 8
var_name(var_2)  # Output will be "var_1" too but Warning will appear

Python中唯一具有规范名称的对象是模块、函数和类,当然,在定义了函数或类或导入了模块之后,不能保证这个规范名称在任何命名空间中都有任何意义。这些名称还可以在创建对象后修改,因此它们可能并不总是特别值得信赖。

如果不递归遍历命名对象的树,就不可能实现你想做的事情;名称是对对象的单向引用。普通或普通的Python对象不包含对其名称的引用。想象一下,如果每个整数、每个字典、每个列表、每个布尔值都需要维护一个表示引用它的名称的字符串列表!这将是实现的噩梦,对程序员没有什么好处。

from __future__ import annotations
import inspect
import pandas as pd


# 변수 이름 가져오기
def getVariableName(variable: str) -> (str | Exception):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()

    df = pd.DataFrame(callers_local_vars)
    df.columns = ['함수명', '값']

    try:
        return df[(df['값'] == variable)].iloc[0]['함수명']
    except Exception as e:
        return e


test = 'Hello World!'

if __name__ == '__main__':
    print(getVariableName(test))