Test the head of expression

19 views
Skip to first unread message

Anton Makarov

unread,
Aug 5, 2022, 2:40:08 PM8/5/22
to sympy
Hi there.
I am trying to test the root of expression tree, for example:
expr = sympify("somefunc(2-5)")
if expr.func.name =="somefunc":
    call_func_1()
else:
    call_func_2()

It works just fine, but when I change the expression, for example, to
expr = sympify("5+6")

Code throws the exception, with error:
AttributeError: type object 'Add' has no attribute 'name'

I don't understand, why Add class has no attribute "name". Or what attribute has all the classes, so I can test the head of any expression without code exception?

What code should I write ?

Anton Makarov

unread,
Aug 5, 2022, 2:46:49 PM8/5/22
to sympy
And one more question: what sympy expression tree classes have the 'name' attribute?

пятница, 5 августа 2022 г. в 21:40:08 UTC+3, Anton Makarov:

Aaron Meurer

unread,
Aug 5, 2022, 4:06:31 PM8/5/22
to sy...@googlegroups.com
Your somefunc is sympified as Function('somefunc'), so you could do

somefunc = Function('somefunc')
if expr.func == somefunc:
...

If you want to test for undefined functions generically you can use

from sympy.core.function import UndefinedFunction
if isinstance(expr.func, UndefinedFunction):
...

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/0987ccd8-66d0-468b-ab1c-9035732cae11n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages