major4x
major4x

Reputation: 442

Python sympy Evaluating When Asked Not To

This works as expected:

>>> from sympy.parsing.sympy_parser import parse_expr 
>>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
(8, 2**3)

This, however, not:

>>> from sympy.parsing.sympy_parser import parse_expr
>>> parse_expr("sqrt(9)"), parse_expr("sqrt(9)", evaluate=False)
(3, 3)

I would expect:

(3, sqrt(9))

Any ideas, why?

Upvotes: 4

Views: 1950

Answers (2)

asmeurer
asmeurer

Reputation: 91620

The evaluate flag to parse_expr only affects the direct evaluation of the expression. sqrt(x) is short for x**Rational(1, 2), which isn't part of the expression parsing.

You can use the with evaluate(False) decorator to prevent the power in the sqrt function from evaluating:

>>> with evaluate(False):
...     print(parse_expr('sqrt(9)', evaluate=False))
sqrt(9)
>>>

(I kept the evaluate=False flag, but it's probably not actually needed)

Upvotes: 4

xenteros
xenteros

Reputation: 15852

evaluate=False only guarantees that

the order of the arguments will remain as they were in the string and automatic simplification that would normally occur is suppressed. (see examples).

It doesn't prevent functions from being executed.

--Documentation

evaluate only refers to operators, not to functions.

Upvotes: 2

Related Questions