I want to code some function that takes 1 input. The input could be numeric (integer, float, Sympy constant like sympy.pi or expression evaluated as real number like sympy.sin(5)), or could be a sympy expression (like x**2-2*y+5.
What I need is to determine:
I have tried .free_symbols and it fails if the input is integer and throws exception.
Also str(input).isnumeric fails if the input is sympy.sin(5).
There is a function in SymPy called sympify whose purpose is to turn non-SymPy objects into SymPy expressions e.g. an int becomes a SymPy Integer etc. If you sympify the input then you can use free_symbols:
In [6]: def inspect(expr):
...: expr = sympify(expr)
...: symbols = expr.free_symbols
...: if not symbols:
...: print(expr, 'has no symbols')
...: else:
...: print(expr, 'has these symbols:', ', '.join(map(str, symbols)))
...:
In [7]: inspect(1)
1 has no symbols
In [8]: inspect(pi)
pi has no symbols
In [9]: inspect(x+y)
x + y has these symbols: y, x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With