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

SymPy解析简单表达式抛出TypeError:涉及AssumptionKeys

问题与错误分析

问题场景

执行以下SymPy代码时,变量定义正常,但调用sympify解析表达式字符串抛出错误:

from sympy import sympify, symbols 
input_str = '100*Q+10*R+5*S+0.6*T'
Q,R,S,T = symbols('Q R S T')

# 执行此语句报错
sympify(input_str)

错误信息

ValueError: Error from parse_expr with transformed code: "Integer (100 )*Q +Integer (10 )*Symbol ('R' )+Integer (5 )*S +Float ('0.6' )*Symbol ('T' )"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "...ipykernel_5652\212826607.py", line 1, in <cell line: 1>
    sympify(input_str)
  File "...\Python\Python310\site-packages\sympy\core\sympify.py", line 496, in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  File "...\Python\Python310\site-packages\sympy\parsing\sympy_parser.py", line 1101, in parse_expr
    raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
  File "...\Python\Python310\site-packages\sympy\parsing\sympy_parser.py", line 1092, in parse_expr
    rv = eval_expr(code, local_dict, global_dict)
  File "...Python\Python310\site-packages\sympy\parsing\sympy_parser.py", line 907, in eval_expr
    expr = eval(
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Integer' and 'AssumptionKeys'

错误原因

  1. SymPy内置对象冲突:SymPy库本身内置了两个特殊对象:
    • Q:属于AssumptionKeys类型,用于符号假设判断(如Q.positive(x));
    • S:属于SingletonRegistry类型,用于访问单例数学符号(如S.Zero、S.Pi)。
  2. 变量名解析冲突:sympify默认会使用当前局部作用域(locals())解析字符串中的变量名。若你的环境中已导入SymPy内置的Q/S(比如通过from sympy import *),或局部变量未完全覆盖内置对象,解析时字符串中的Q/S会指向SymPy内置的非Symbol对象,而非你用symbols()创建的符号变量。
  3. 操作类型不兼容:内置的AssumptionKeys/SingletonRegistry对象不支持与Integer执行乘法运算,因此触发TypeError。

从转换后的代码也能佐证这一点:R和T被解析为新的Symbol实例,但Q和S直接使用了现有变量——说明这两个变量指向的不是你定义的符号,而是SymPy内置对象。

解决办法

  • 更换变量名:避免使用SymPy内置的特殊名称,比如将Q改为q、S改为s:
    q,r,s,t = symbols('q r s t')
    input_str = '100*q+10*r+5*s+0.6*t'
    sympify(input_str)
    
  • 显式指定局部变量:调用sympify时通过local_dict参数明确传入自定义的符号变量:
    sympify(input_str, local_dict={'Q': Q, 'R': R, 'S': S, 'T': T})
    
  • 避免全局导入:不要使用from sympy import *,而是按需导入所需模块,防止内置对象污染局部作用域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:43:04