1

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?

Zizouz212
  • 4,908
  • 5
  • 42
  • 66
Alvahix
  • 13
  • 2

2 Answers2

0

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)
Zizouz212
  • 4,908
  • 5
  • 42
  • 66
0

Or:

ureg = UnitRegistry()
user_value = input()
unit = vars(ureg)[user_value] # this is a variable defined by user
step = 8 * unit
print(step)

Or:

eval('ureg.%s()'%user_value)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Thank you! I kept getting errors on the first part, got the second one to work! What does `eval()` do? – Alvahix Aug 03 '18 at 06:10
  • @U9-Forward Wrong, `eval` evaluates a python expression. Anything from `1 + 1` to `os.system(MALICOUS_CODE)`. It's a security risk, and it exposes your program to vulnerabilities, as well as unwanted errors. – Zizouz212 Aug 05 '18 at 07:36
  • @Zizouz212 Yeah i know, it is bad practice to use `eval` and `exec`, from here it explains all:[Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – U13-Forward Aug 06 '18 at 01:01