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

如何在Python函数内同时以字符串和值形式使用传入参数?

解决方案:获取参数原表达式与实际值的Python函数

要实现同时获取参数的原表达式字符串和实际求值结果,核心思路是通过Python的inspect模块获取调用上下文的源代码,再用AST解析提取参数表达式——因为函数直接接收的是参数求值后的结果,必须回溯调用栈才能拿到原代码。

实现代码

import inspect
import ast

def func(arg):
    # 获取当前函数的上一层调用栈帧
    caller_frame = inspect.currentframe().f_back
    # 读取调用者的源代码
    caller_source = inspect.getsource(caller_frame)
    # 解析源代码为AST语法树
    ast_tree = ast.parse(caller_source)
    
    # 遍历AST找到func的调用节点,提取参数表达式
    arg_expr = None
    for node in ast.walk(ast_tree):
        if isinstance(node, ast.Call) and hasattr(node.func, 'id') and node.func.id == 'func':
            arg_expr = ast.get_source_segment(caller_source, node.args[0])
            break
    
    # 格式化输出
    print(f'the value of {arg_expr} is:', arg)

测试示例

# 整数参数测试
func(2)
# 输出: the value of 2 is: 2

# Pandas Series参数测试
import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 3]})
func(df['col1'])
# 输出: the value of df['col1'] is: 0    1
# 1    2
# 2    3
# Name: col1, dtype: int64

# 表达式参数测试
func(2 + 4)
# 输出: the value of 2+4 is: 6

注意事项

  • 该方法要求调用代码的源代码可被inspect模块读取,因此在交互式环境(Python解释器、IPython)或本地脚本中有效,编译后的字节码、压缩代码场景下可能失效。
  • 如果同一行存在多个func调用,当前逻辑会匹配第一个调用的参数,建议确保每行仅包含一个func调用。
  • 支持绝大多数常见表达式,包括嵌套函数调用、属性访问等复杂场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:25:04