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

Python 2.7中如何在函数内部获取传入参数对应的外部变量名?

Python 2.7 实现打印变量名与前N条样本的解决方案

核心实现代码

import inspect
import cPickle as pickle # Python2.7下适配的pickle模块,性能优于原生pickle

def sample_data(data_name, n):
    """print top N of the data with variable name
    """
    # 获取调用栈的上层帧信息
    frame = inspect.currentframe().f_back
    # 从栈帧中获取调用该函数的代码行
    call_code = inspect.getframeinfo(frame).code_context[0].strip()
    # 提取第一个参数的内容作为变量标识
    arg_name = call_code.split('(')[1].split(',')[0].strip()
    
    # 适配pkl文件场景:如果传入的是.pkl结尾的路径字符串,自动读取文件内容
    if isinstance(data_name, basestring) and data_name.endswith('.pkl'):
        with open(data_name, 'rb') as f:
            data = pickle.load(f)
        print('{} (loaded from {}): {}'.format(arg_name, data_name, data[:n]))
        return
    
    # 普通变量场景
    print('{}: {}'.format(arg_name, data_name[:n]))

使用示例

# 示例1:传入已加载的变量
user_feature = [1,2,3,4,5,6,7,8]
sample_data(user_feature, 3)
# 输出:user_feature: [1, 2, 3]

# 示例2:直接传入pkl文件路径,无需提前加载
sample_data('train_data.pkl', 5)
# 输出:'train_data.pkl' (loaded from train_data.pkl): [样本1, 样本2, 样本3, 样本4, 样本5]

说明

  • 该实现通过解析函数调用的代码上下文提取实参名称,不需要依赖eval,完全适配Python2.7环境
  • 内置pkl文件自动读取逻辑,无需提前手动加载pickle文件即可直接查看内容
  • 若传入的第一个参数是表达式而非直接变量名,会直接打印表达式内容作为标识,符合调试场景的使用需求
  • 若数据对象不支持切片操作,可自行添加try...except块做异常捕获,避免运行报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 05:48:03