Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use user input to choose a parameter name and an attribute name?

Tags:

python

I'm using a library called unit-convert. The interface looks like this:

# Bytes to terabytes
>>> UnitConvert(b=19849347813875).tb

Suppose I have strings taken from user input (omitting the input code) like so:

input_value_unit = 'b'
output_value_unit = 'tb'

How can I substitute these into the call?

I tried using UnitConvert(input_value_unit=user_input_value).output_value_unit, but this doesn't use the string values.

like image 965
Roger Brown Avatar asked Dec 06 '25 20:12

Roger Brown


1 Answers

Code like function(x=1) doesn't care if there's a variable named x naming a string; the x literally means x, not the x variable. Similarly for attributes: x.y doesn't care if there is a y variable naming a string; it will just get the y attribute of x.

However, we can use strings to specify both of these things "dynamically".

To replace the b in the example, we need to use a string as a keyword argument name. We can do this by making a dictionary for the keyword arguments, and then using ** to pass them. With a literal string, that looks like: UnitConvert(**{'b': ...}).

To replace the tb, we need to use a string as an attribute name. We can do this by using the built-in getattr to look up an attribute name dynamically. With a literal string, that looks like: getattr(UnitConvert(...), 'tb').

These transformations let us use a literal string instead of an identifier name.

Putting it together:

# suppose we have read these from user input:
input_value_unit = 'b'
output_value_unit = 'tb'
input_amount = 19849347813875
# then we use them with the library:
getattr(UnitConvert(**{input_value_unit: input_amount}), output_value_unit)
like image 178
Karl Knechtel Avatar answered Dec 08 '25 10:12

Karl Knechtel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!