-1

I have a list for variables of fruits in a python script:

VariableScript.py:

variableColorApple = "Red"
variableWeightApple = ["5", "6", "7"]
variablePriceApple = ["10", "15", "20"]
variableColorApple = "Orange"
variableWeightOrange =["8", "9", "10"]
variablePriceOrange =["10", "15", "20"]
#...

And I have another script, where I use user input (user's fruit choice), to run my analysis. I want to write only one script that I can runregardless of the user's fruit selection. So I could avoid if else statements and long scripts.

I thought I could use string operators to import variables, but with string operators python doesn't find the variable in VariableScript module. What else I can try?

I have also already tried operator.getattr(). But then I couldnt access the items in the gettattr().

Just to keep it simple and executable: Let's say the users' input is "Apple" and I just want to print the color of apple from VariablesScript.py. My code is:

from VariableScript import VariablesScript as Variables

userInput = "Apple"
print(Variables.variableColor + UserInput)`

Any idea how can I get the color or apple without actually writing apple?...

o.d.rinani
  • 23
  • 8
  • 7
    It sounds like you need a `dict` with strings as keys. – quamrana Jan 19 '23 at 14:27
  • `dict` could also prevent facepalms like `variableColorApple = "Orange"` – matszwecja Jan 19 '23 at 14:30
  • Do the answers to this [question](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) help at all? – quamrana Jan 19 '23 at 14:38
  • `Variables.variableColor + UserInput` is going to get the value of `Variables.variableColor` and then based on whatever datatype it is, call its `__add__(self, other)` function with UserInput as other. In this case, it will either append the strings, or throw a ValueError – nigh_anxiety Jan 19 '23 at 14:40

2 Answers2

2

So what you're asking to do is technically possible, but it is definitely un-Pythonic and really not a stable design.

Here's how to get your code to work:

from VariableScript import VariablesScript as Variables

userInput = "Apple"
try:
    var = "variableColor" + userInput
    value = getattr(Variables, var)
except AttributeError as e:
    print(f"The variable '{var}' is not defined.")
else:
    print(value)

A much better solution here would be to use a data structure such as a dictionary, which has string key lookup.

#variables.py

fruits = {
    "apple" : {
       "color": "Red",
       "weight": ["5", "6", "7"],
       "price" : ["10", "15", "20"]
       },
    "orange" : {
        "color": "Orange",
        "weight": ["8", "9", "10"],
        "price" : ["10", "15", "20"]
        }
}


#main.py

from variables import fruits

user_input = "Apple"

fruit_data = fruits.get(user_input.lower())
if fruit_data is None:
    fruit_folor = f"{user_input} was not found"
else:
    fruit_color = fruit_data["color"]

print(fruit_color)

Edit: added safeguard for case where fruits.get(user_input.lower()) returns None and fixed my brackets.

You may also want to look into DataClasses or NamedTuples as a data structure to use for each fruit. Also, if the weights and prices lists are meant to be in sync, then perhaps they should be a in a dictionary with weight as the key, and price as the value, or it should be a single list of tuples.

nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12
0

Use exec() function to execute a string as Python code.

from VariableScript import VariablesScript as Variables

userInput = "Apple"
variableColor = 'variableColor' + userInput
exec(f'color = Variables.{variableColor}')
print(color)

or use a dictionary to store the variable names and their corresponding values:

from VariableScript import VariablesScript as Variables

fruit_data = {
    'Apple': {'color': Variables.variableColorApple, 'weight': Variables.variableWeightApple, 'price': Variables.variablePriceApple},
    'Orange': {'color': Variables.variableColorOrange, 'weight': Variables.variableWeightOrange, 'price': Variables.variablePriceOrange},
}

user_input = 'Apple'
color = fruit_data[user_input]['color']
print(color)
Agan
  • 447
  • 2
  • 12
  • A couple of major downsides to using `exec` like this: 1) If you don't define `color` anywhere else, then most IDEs/linters are going to complain that `color` is not defined. 2) Still need to use try/except to catch an AttributeError if the user input is not an exact match to one of the variables defined. If OP really doesn't want to use a dict or other structure, using `hasattr()` and `getattr()` is probably better than abusing `exec()`, which could leave a program open to code injection. – nigh_anxiety Jan 19 '23 at 15:03
  • That's right, thnx for feedback. – Agan Jan 19 '23 at 15:19