Handle Python reserved words in a sympy parse_expr?

444 Views Asked by At

If I parse an expression containing lambda, I get an error even though Symbol("lambda") is valid:

>>> sympy.Symbol("lambda")
lambda
>>> sympy.parse_expr("1 + lambda")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "xxx/lib/python3.7/site-packages/sympy/parsing/sympy_parser.py", line 1008, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "xxx/lib/python3.7/site-packages/sympy/parsing/sympy_parser.py", line 903, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Integer (1 )+lambda
                      ^
SyntaxError: invalid syntax
>>> sympy.parse_expr("1 + _lambda")
_lambda + 1

I'd like to allow users of my code to name their variables how ever they like. Is there a way to support this?

If not, I could work out some other way to put an underscore in front of reserved words.

I'm using Sympy 1.6 if that matters.

1

There are 1 best solutions below

1
On

Searching sympy for reserved, I found a suggestion to use lamda (without the 'b'). https://docs.sympy.org/latest/tutorial/matrices.html?highlight=reserved

In [146]: lamda = symbols('lamda')

In [147]: from sympy.parsing.sympy_parser import standard_transformations

In [148]: parse_expr("1/2+lamda", transformations=standard_transformations)
Out[148]: λ + 1/2