Taking a quick look at Unum
's documentation, it appears that you should be able to do something like this with eval
:
from unum.units import * # Load a number of common units.
distance = 100*m
time = eval('9.683*s')
speed = distance / time
print(speed)
If you do this though, make sure that you read the documentation on eval
and how you can pass local and global mappings in order to restrict the namespace access to make it safer -- especially if you ever plan on releasing this code to the outside world. You'll probably also want to check the strings for underscores (_
) and not allow those to be passed to eval
.
As noted by kindall, importing *
is usually not good style. Here's a slightly more safe alternative which avoids importing from *
:
import unum.units
safe_dict = dict((x,y) for x,y in unum.units.__dict__.items() if '__' not in x)
safe_dict['__builtins__'] = None
def convert(s):
if '__' in s:
raise ValueError("Won't do this with underscores...it's unsafe")
return eval(s,safe_dict)
Note that I cut out the __
methods as advocated in this post