I have a SymPy symbolic variable:
from sympy import symbols
You cannot dynamically add an attribute to a
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
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
__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
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?