0

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.

amos
  • 5,092
  • 4
  • 34
  • 43
  • The problem isn't with the `symbol`, but with the Python variable that usually looks the same. Python variables cannot be reserved words. Read the block about symbol names here https://docs.sympy.org/latest/tutorial/gotchas.html. And study https://docs.sympy.org/latest/modules/parsing.html. It probably has parameters that let you control the translation from symbol names to variables in the global dict. – hpaulj Feb 03 '21 at 19:39
  • The only comment I find is confirmation that using `lambda` is a syntax error: https://docs.sympy.org/latest/modules/parsing.html#sympy.parsing.sympy_parser.lambda_notation but no guidance on if it's possible to parse `"lambda"` as a symbol. – amos Feb 04 '21 at 02:05

1 Answers1

0

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
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • ah, good find! that didn't turn up in my searches. I think the answer to my question is: there is no way to use `lambda`, I'm going to have to either disallow that spelling from my users or implement a variable name mapping. – amos Feb 04 '21 at 14:48