Sympy Function with string

46 Views Asked by At

I would like to have a custom class which in principle behaves like a sympy Function but holds also a string. However, when I create a derived class from sympy Function the following code produces an error ('could not parse 'a b'):

import sympy as sp
class testClass(sp.Function):
    pass
a = testClass('a b')

I understand that the sympify function is called and has problems to parse 'a b' to a sympy expression. As a possible workaround for my needs I found that

a = testClass(sp.Symbol('a b'))

would work. Nevertheless, it would be interesting to avoid the use of Symbol here. In my understanding, to make this working I would have to reimplement the __new__ method. Is this correct or is there an easy solution?

1

There are 1 best solutions below

0
Michael Gfrerer On

Based on the comment of Oscar Benjamin the following works for me:

import sympy as sp
class testClass(sp.Function):
    def __new__(cls, *args, **kwargs):
        new_args = (sp.Symbol(x) if isinstance(x, str) else x for x in args)
        return super().__new__(cls, *new_args, **kwargs)
    # other methods...

c = testClass('a b')