Admia Admia - 3 months ago 5
Python Question

Add a new field to the sympy symbolic variable

I have a SymPy symbolic variable:

from sympy import symbols

How can I add a new field to the symbolic variable



You cannot dynamically add an attribute to a Symbol.

It would most likely be a bad idea because SymPy assumes that it can replace expressions which compare as equal. So if you created two symbols and stored an attribute dynamically in one (supposing this were possible)

a1 = Symbol('a') 
a2 = Symbol('a') 
a1.something = 0 

Then SymPy would take the liberty of swapping a1 and a2 whenever it felt like doing so as they compare equal (a1 == a2), which would certainly have unintended consequences.

If you take a look at the source code, you can see that a Symbol defines __slots__ in its class for performance reasons, which effectively tells the interpreter "These are all the instance attributes in this class". This is why you cannot dynamically add attributes to a Symbol.

A possible alternative could be to create a subclass of Symbol that stores your desired attributes in its args, such that they are factored into the equality comparison of your subclass objects.

For an extended discussion on the topic which I somewhat paraphrased here, see the Google thread: How to equip a Symbol with an additional attribute?