Home > Mobile >  Simple expression parsing throws a TypeError referencing 'AssumptionKeys'
Simple expression parsing throws a TypeError referencing 'AssumptionKeys'

Time:12-19

I'm trying to get sympy to calculate the result of what should be a simple expression with three substitutions, but I'm coming up against an error I've not encountered before.

>>> 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')

The above code works fine, but when I run the string though sympify, I get the following error:

>>> 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'

What on earth could be causing this error with such a simple expression?

CodePudding user response:

The problem is the character "Q". Once it gets sympified it will represent AssumptionKeys. You probably need to use something like this, in which we ask sympify to replace the character "Q" with symbol Q:

Q = symbols("Q")
sympify('100*Q 10*R 5*s 0.6*T', locals={"Q": Q})

CodePudding user response:

Capital letters are reserved for other purposes in SymPy eg the singleton class is accessible as S while Q is a property of Sympy. Replace your capital letters by lower case letters and it should work: q, r, s, t = symbols('Q R S T') input_str = '100q 10r 5s 0.6t' sympify(input_str)

  • Related