Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one check if a variable is a sympy expression?

Tags:

python

sympy

I wanted to check a python variable is a sympy expression. Its easy to check if its a sympy variable with:

isinstance(arg, symbol.Symbol)

but I can't find how to do:

isinstance(arg, sympy.Expression)

is it possible to check if a python variable holds a sympy expression or a variable?


as a quick check I did:

expr2 = x-y
type(expr2)
<class 'sympy.core.add.Add'>

but I don't want to have a giant series if statement clause checking each possible type of maths expression. Seems redundant/silly.


It would also nice to be able to detect when a variable is of any type of sympy related thing and then act on it (and then maybe later check if its an expression or something more detailed...)

like image 470
Charlie Parker Avatar asked Oct 23 '25 15:10

Charlie Parker


1 Answers

I think you simply need sympy.Expr instead of sympy.Expression:

In [164]: expr2
Out[164]: x - y

In [165]: type(expr2)
Out[165]: sympy.core.add.Add

but if we look at the __bases__ of this type:

In [166]: type(expr2).__bases__
Out[166]: (sympy.core.expr.Expr, sympy.core.operations.AssocOp)

And so:

In [167]: isinstance(2, sympy.Expr)
Out[167]: False

In [168]: isinstance(x, sympy.Expr)
Out[168]: True

In [169]: isinstance(x-y, sympy.Expr)
Out[169]: True
like image 174
DSM Avatar answered Oct 25 '25 03:10

DSM