Possible to add descriptions to symbols in sympy?

2020-03-17 04:11发布

问题:

I seek a functionality in sympy that can provide descriptions to symbols when needed. This would be something along the lines of

>>> x = symbols('x')
>>> x.description.set('Distance (m)')
>>> t = symbols('t')
>>> t.description.set('Time (s)')
>>> x.description()
'Distance (m)'
>>> t.description()
'Time (s)'

This would be useful because it would enable me to keep track of all my variables and know what physical quantities I am dealing with. Is something like this even remotely possible in sympy?

EDIT

I don't think this is a duplicate because the __doc__ attribute for symbols appears to be immutable. Consider the following:

>>> print(rhow.__doc__)

    Assumptions:
       commutative = True

    You can override the default assumptions in the constructor:

from sympy import symbols
A,B = symbols('A,B', commutative = False)
bool(A*B != B*A)
    True
bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
    True

>>> rhow.__doc__ = 'density of water'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-87-bfae705941d2> in <module>()
----> 1 rhow.__doc__ = 'density of water'

AttributeError: 'Symbol' object attribute '__doc__' is read-only

Indeed a .__doc__ attribute exists, but I cannot change it for my purposes. It is read only.

回答1:

You may inherit Symbol class and add your own custom property like here:

from sympy import Symbol, simplify

# my custom class with description attribute
class MySymbol(Symbol):
    def __new__(self, name, description=''):
        obj = Symbol.__new__(self, name)
        obj.description = description
        return obj

# make new objects with description
x = MySymbol('x')
x.description = 'Distance (m)'
t = MySymbol('t', 'Time (s)')
print( x.description, t.description)

# test
expr = (x*t + 2*t)/t
print (simplify(expr))

Output:

Distance (m) Time (s)
x + 2


标签: python sympy