On 05/19/2015 02:39 AM, Aaron Meurer wrote: > On Mon, May 18, 2015 at 12:29 PM, Joachim Durchholz <[email protected]> > wrote: >> Am 18.05.2015 um 15:56 schrieb Carsten Knoll: >>> >>> I want to equip an Symbol with an additional attribute to store some >>> specific information right in place. >>> >>> For 'normal' Python classes it is no problem to dynamically create an >>> additional attribute for an already existing instance. >>> >>> However, for sympy Symbols if I try >>> >>> x = Symbol('x') >>> x.k = 0 >>> >>> I get the error >>> >>> AttributeError: 'Symbol' object has no attribute 'k' >> >> >> That happens because we use __slots__ for performance reasons. >> However, storing attributes in that way is a bad idea in general, because >> you risk name conflicts with future versions of SymPy. (That's also the >> reason why using subclasses to extend a library tends to break over time.) > > I'm not so sure about this. > > The real reason that storing an attribute on x is a bad idea is that > SymPy implicitly assumes that it can replace one expression with the > same expression if the two are equal, so, e.g., if you had > > x1 = Symbol('x') > x2 = Symbol('x') > x1.k = 0 > > and supposing it worked, along with x1 == x2 giving True, then SymPy > would assume that it has the freedom at any point to swap x1 with x2 > and visa versa (and indeed, it does do this quite a bit with the > cache).
Thanks for pointing that out. I will add it to my tests. > > I think what you really want to do is create a subclass of Symbol that > stores the attributes in .args, so that they become part of the > equality of the object. Joachim's alternative 1 (store the > information separately) also sounds like a good one (and probably much > simpler to implement). Subclassing and adding attributes in .args indeed seems more complicated. I will stick with the external dict solution. Regards, Carsten. -- You received this message because you are subscribed to the Google Groups "sympy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/sympy. To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/555B0666.3060405%40gmx.de. For more options, visit https://groups.google.com/d/optout.
