Units
A solution would be to gather all units from the SymPy units
module and use them to substitute the symbols created by sympify
>>> import sympy.physics.units as u
... subs = {}
... for k, v in u.__dict__.items():
... if isinstance(v, Expr) and v.has(u.Unit):
... subs[Symbol(k)] = v # Map the `Symbol` for a unit to the unit
>>> # sympify returns `Symbol`s, `subs` maps them to `Unit`s
>>> print sympify('yard*millimeter/ly').subs(subs)
127*m/1313990343414000000000
If the symbol is not in units
it will just be printed as unknown symbol (for instance barn
)
>>> print sympify('barn/meter**2').subs(subs)
barn/m**2
But you can always add stuff to the subs
dictionary.
>>> subs[Symbol('almost_meter')] = 0.9*u.meter
... sympify('almost_meter').subs(subs)
0.9*m
SI prefixes don't work exactly like you want them. You will need to add a multiplication sign (or hope that it is a common unit like km
which is explicitly implemented). Moreover, as they are not Unit
instances but rather Integer
instance you will have to add them to subs
:
>>> import sympy.physics.units as u
... subs = {}
... for k, v in u.__dict__.items():
... if (isinstance(v, Expr) and v.has(u.Unit)) or isinstance(v, Integer):
... subs[Symbol(k)] = v
>>> print sympify('mega*m').subs(subs)
1000000*m
For unicode you might need some preprocessing. I do not think SymPy makes any promises about unicode support.
If you implement new Unit
s, please consider making a pull request with them on github. The file to edit should be sympy/physics/units.py
.
Whitespaces and implicit multiplication
In the dev version of SymPy you can find code for assuming implicit multiplications where appropriate whitespaces are written:
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication_application)
>>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
... transformations=(standard_transformations +
... (implicit_multiplication_application,)))
3*x*y*z + 10*sin(x**2)**2 + tan(theta)
Security
sympify
uses eval
which is exploitable if you are going to use it for a web facing app!