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

如何将字典解构为函数参数传入eval命令中

问题解答

你现有代码的核心问题是Python的字典解构语法**xxx属于代码执行层面的语法,不能直接嵌入到要执行的字符串内容里,直接拼接只会把**third_party当成普通文本,eval执行时会因为找不到对应变量、语法不符合要求报错,同时也不需要依赖itemgetter实现动态参数传递。

推荐方案(完全避免eval,更安全高效)

直接用Python内置的getattr动态获取目标方法,不需要拼接执行字符串,还能避免eval带来的代码注入风险,完美适配字典键动态变化的场景:

def sample(third_party):
    '''
    :param third_party: 字典,键的数量和名称不固定
    '''
    # 确保你要调用的initial模块已经提前正确导入
    # type是必传键
    tp_type = third_party['type']
    if tp_type[-1] == 's':
        type_execution = tp_type + '_s'
    else:
        type_execution = tp_type + 's'
    # 动态获取目标类/对象
    target_cls = getattr(initial.constant.command, type_execution)
    # 直接解构字典传参,不需要提前知道字典的键
    target_cls.create(**third_party)

特殊场景需使用eval的替代方案(极不推荐,仅做参考)

如果有不可抗因素必须使用eval,不要把字典内容拼到执行字符串里,而是通过eval的命名空间参数传递变量,避免转义错误和注入风险:

def sample(third_party):
    '''
    :param third_party: 字典,键的数量和名称不固定
    '''
    tp_type = third_party['type']
    if tp_type[-1] == 's':
        type_execution = tp_type + '_s'
    else:
        type_execution = tp_type + 's'
    # 执行字符串里仅写参数占位名
    eval_statement = f"initial.constant.command.{type_execution}.create(**tp)"
    # 通过局部命名空间传参,不用把字典内容拼到字符串中
    eval(eval_statement, globals(), {"tp": third_party})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:54:00