简体   繁体   中英

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

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...)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM