1

I'm working on a fun project with my friend and we're trying to figure out how to get a specific variable from a file using user input.

Example:

In pokemonList.py file

charmander = "fire"
squirtle = "water"

In main.py file

import pokemonList
pokemon = input("select a pokemon: ")
print(pokemonList.pokemon)

When I try that the program thinks I'm trying to get a variable called "pokemon" from the file. Is there any way to do this?

DontAsk_
  • 139
  • 2
  • 12
  • 1
    You want to use a [`dict`](https://docs.python.org/3/tutorial/datastructures.html#dictionaries). Or perhaps something more advanced like the [`configparser`](https://docs.python.org/3/library/configparser.html) package. – 0x5453 Oct 16 '20 at 17:26
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – ggorlen Oct 16 '20 at 17:36

2 Answers2

2

Assuming that names are unique, I think a dictionary is a sensible approach:

in pokemonList.py:

pokemon = {"charmander" : "fire",
           "squirtle" : "water"}

in main.py:

import pokemonList

pokemon = input("select a pokemon: ")
print(pokemon, " ", pokemonList.pokemon[pokemon])
Andrew
  • 1,072
  • 1
  • 7
  • 15
0

There are a couple of ways to achieve what you need.

  1. Instead of saving the variables just as variables, save them as a dictionary, like this:

pokemonList.py:

pokemon = {"charmander": "fire",
           "squirtle": "water"}

main.py:

import pokemonList

pokemon = input("select a pokemon: ")
print(pokemonList.pokemon[pokemon])
  1. You can use the eval function to get the values (very unsafe and not recommended):

pokemonList.py:

charmander = "fire"
squirtle = "water"

main.py:

import pokemonList
pokemon = input("select a pokemon: ")
print(eval("pokemonList."+pokemon))
Yuval.R
  • 1,182
  • 4
  • 15
  • The `eval` approach is poor design. Code shouldn't be tied down to what its variable names are literally and `eval` is a security hole, not to mention slow. Looking the user input in `globals` is a bit better but still pretty awful. – ggorlen Oct 16 '20 at 17:33
  • Option 2 is _extremely_ unsafe. Probably it's "ok" for your current task, but not doing things like `eval(input())` is the bare minimum of program security. – ShapeOfMatter Oct 16 '20 at 17:35
  • Correct, this is why it is the second way, but I will add that this is unsafe and not recommended. – Yuval.R Oct 16 '20 at 17:35
  • Or just remove it entirely ;-) – ggorlen Oct 16 '20 at 17:35
  • Here's an example string you can input to see the severity here: `charmander.index(eval('__import__("os").system("echo I wiped your harddrive")'))`. – ggorlen Oct 16 '20 at 17:47