You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中编写函数获取列表/DataFrame的变量名字符串

实现获取变量名字符串的Python函数get_name

Python中对象本身不会存储它所绑定的变量名,变量只是指向对象的引用,所以要实现这个需求,需要通过分析调用上下文的源码来反向查找变量名。以下是可行的实现方案:

函数实现

import inspect
import re

def get_name(var):
    # 获取调用栈的上一层帧(即调用get_name的代码所在帧)
    caller_frame = inspect.currentframe().f_back
    # 提取调用行的源码文本
    caller_source = inspect.getframeinfo(caller_frame).code_context[0].strip()
    # 正则匹配get_name函数调用中的参数部分
    match_result = re.search(r'get_name\((.*?)\)', caller_source)
    if match_result:
        # 返回匹配到的变量名(去除首尾空格)
        return match_result.group(1).strip()
    # 匹配失败时返回None
    return None

测试示例

# 测试列表变量
li = [1]
print(get_name(li))  # 输出: 'li'
print(f'{get_name(li)}')  # 输出: 'li'

# 测试DataFrame变量
import pandas as pd
df = pd.DataFrame({'col': [1, 2, 3]})
print(get_name(df))  # 输出: 'df'

注意事项

  • 该实现依赖调用时的源码格式,仅支持直接传入变量的场景(如get_name(li)),不支持复杂表达式(如get_name(li[0])、get_name(li + [2]))。
  • 在某些编译优化环境或无源码上下文的场景(如部分打包后的程序),可能无法获取调用行源码,此时函数会返回None。
  • 不支持嵌套调用,比如get_name(get_name(li))会返回get_name(li)而非li。

内容的提问来源于stack exchange,提问作者younghyun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:02:42