Behaviour of symbols with and without assumptions in sympify

46 views
Skip to first unread message

ludi

unread,
Feb 14, 2020, 10:03:02 AM2/14/20
to sympy
Hi

If I do

a=Symbol('a', real=True)
b=Symbol('b')

and do

solve(a**2-1,a)
I get


solve(a**2+1,a)
I get


solve(sympify("a**2+1"),a)
solve(sympify("a**2-1"),a)
solve(sympify("b**2-1"),b)
solve(sympify("b**2+1"),b)

So solve(sympify("something with a"), a)  will always return the empty list.
Why is that?
Any argument I could pass to sympify to amend this?

The same its true for solveset.

Kalevi Suominen

unread,
Feb 14, 2020, 10:43:42 AM2/14/20
to sympy
Hi,
sympify('a') will return a symbol with no assumptions, which is different from a as defined. You can amend this by passing a dictionary with intended translations:
>>> from sympy import sympify, Symbol
>>> a = Symbol('a', real=True)
>>> sympify('a') == a
False
>>> sympify('a', {'a': a}) == a
True

Kalevi Suominen

ludi

unread,
Feb 14, 2020, 6:25:57 PM2/14/20
to sympy
Thanks a lot

I read about locals and individual dictionaries, but I didn't realize that it would affect "already defined" Symbols.
It is a little bit confusing that 'a' and 'a' can be not the same thing.

But now everything works as expected, thanks again.

Aaron Meurer

unread,
Feb 14, 2020, 6:55:20 PM2/14/20
to sympy
sympify() works independently of what you already have defined. So for
instance,

x = 1
print(sympify('x')) # prints x

This produce Symbol('x'), not 1. If you want it to use what you
already have defined, you can pass locals() as the second argument to
sympify()

x = 1
print(sympify('x', locals()) # prints 1

The best recommendation is in general to avoid sympify, unless you are
processing arbitrary strings. Instead, build your expression up
directly using Python operations, like in your first examples.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/5d9325aa-6eb4-4340-af0d-5e0f3a93c419%40googlegroups.com.

ludi

unread,
Feb 15, 2020, 4:47:01 AM2/15/20
to sympy
On Saturday, 15 February 2020 00:55:20 UTC+1, Aaron Meurer wrote:
...

The best recommendation is in general to avoid sympify, unless you are
processing arbitrary strings
....

Thanks for the reply, but as I am processing user-input I think there is no way around sympify.

Chris Smith

unread,
Feb 20, 2020, 1:07:54 PM2/20/20
to sympy
If you are solving univariate expressions you don't need to pass the symbol:
>>> solve(S('x**2 -1'))
[-1, 1]
Reply all
Reply to author
Forward
0 new messages