SymPy: How can I check, if symbol is a constant or a variable?

Viewed 424

In sympy, I want to create a constant e.g. to represent the speed of light. Thus I initialize c with the keyword constant=True.

Later I want to check, if a symbol is a constant or a variable. Unexpectedly the command c.is_constant() outputs False.

c = Symbol( 'c' , constant=True, real=True )
c.is_real       # outputs True as expected.
c.is_constant() # outputs False. This is unexpected !

How can I check, if a symbol is a constant or a variable ?

2 Answers

Instead of creating a Symbol, creating a Quantity object should do the job. The code example below does what you are trying to do.

from sympy.physics.units.quantities import Quantity

c = Quantity('c')
print(c.is_constant())

Output:

True

In case you need something else, or more customized, you may try doing something similar to what Sympy does for constant values such as e and pi, you can find the source code for that here:

https://github.com/sympy/sympy/blob/46e00feeef5204d896a2fbec65390bd4145c3902/sympy/core/numbers.py#L3421-L3578

And for more information on why the is_constant method was returning False, check out this

https://docs.sympy.org/latest/modules/core.html#sympy.core.expr.Expr.is_constant

Look what happens when I construct a symbol with various keywords:

In [93]: c = Symbol( 'c' , constant=True, real=True, foobar=True )
In [94]: c._assumptions
Out[94]: 
{'constant': True,
 'real': True,
 'extended_real': True,
 'hermitian': True,
 'commutative': True,
 'imaginary': False,
 'finite': True,
 'complex': True,
 'infinite': False,
 'foobar': True}

Those keywords, plus some defaults, are put in a dict. I included your constant, and random choice of my own foobar. Neither has special meaning.

The is_constant method does not look for this assumption value:

def is_constant(self, *wrt, **flags):
    if not wrt:
        return False
    return not self in wrt

We have to study its docs to see what a wrt is.

Specifying an assumption is one thing, actually using it is quite another.

Related