How to check the expression

33 views
Skip to first unread message

Anton Makarov

unread,
Jul 22, 2022, 12:51:41 PM7/22/22
to sympy
Hi, I am new to sympy. I am trying to understand what is the best practice to check head of expression? For example:
expr = sympify("somefunc(1-x)")
How to understand that head of expr is somefunc? I can do it like this:
if str(expr.func) == "somefunc"
Is this a best practice or there is a better way to do this?
And by the way, if I have the expression:
expr = sympify("x")
How can I check that expr is some variable (not necessary "x", but in more broader sense)?
Or:
expr = sympify("5.5777")
how to check that expr is some number?

Aaron Meurer

unread,
Jul 22, 2022, 1:00:18 PM7/22/22
to sy...@googlegroups.com
On Fri, Jul 22, 2022 at 10:51 AM Anton Makarov <antonv...@gmail.com> wrote:
>
> Hi, I am new to sympy. I am trying to understand what is the best practice to check head of expression? For example:
> expr = sympify("somefunc(1-x)")
> Is this a best practice or there is a better way to do this?

Undefined functions created from sympify will have the
UndefinedFunction metaclass, which you can test directly with

>>> from sympy.core.function import UndefinedFunction
>>> isinstance(sympify("somefunc(1-x)").func, UndefinedFunction)
True
>>> sympify("somefunc(1-x)").func.name == 'somefunc'
True

Or alternately you can just check

>>> sympify("somefunc(1-x)").func == Function('somefunc')
True

Note that this won't apply to functions that are predefined in SymPy like sin().

> How to understand that head of expr is somefunc? I can do it like this:
> if str(expr.func) == "somefunc"

> And by the way, if I have the expression:
> expr = sympify("x")
> How can I check that expr is some variable (not necessary "x", but in more broader sense)?

isinstance(expr, Symbol)

> Or:
> expr = sympify("5.5777")
> how to check that expr is some number?

isinstance(expr, Number)

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/654926aa-8c56-4a27-8ca6-68f389273475n%40googlegroups.com.

Anton Makarov

unread,
Jul 22, 2022, 1:18:38 PM7/22/22
to sympy
thank you

пятница, 22 июля 2022 г. в 20:00:18 UTC+3, asme...@gmail.com:
Reply all
Reply to author
Forward
0 new messages