I'm currently attempting to write a program that takes in a user input of units and magnitude and converts them to a user defines the unit. So basically just a unit converter (still doing beginner projects with Python).
But for the module pint
, it uses a dot separator as the way to get the units, like so:
from pint import *
ureg = UnitRegistry()
dist = 8 * ureg.meter
print(dist)
>>> 8 meters
Now 8 is tied to meters. But say I want to let the user define the unit. So have a variable defined by an input attached to ureg
like so:
from pint import *
ureg = UnitRegistry()
inp = input()
>>>inp = meter
unit = ureg.inp # this is a variable defined by user
step = 8 * unit
print(step)
>>>AttributeError: 'UnitRegistry' object has no attribute '_inp_'
The problem is python thinks I'm trying to access an attribute called inp
from ureg
, which doesn't exist. if inp=meters
, why won't it work as ureg.meters
worked? How can you attach variables to call attributes from a module?
You could use getattr(object, name)
:
ureg = UnitRegistry()
user_value = input()
unit = getattr(ureg, user_value) # this is a variable defined by user
step = 8 * unit
print(step)