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?

2

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your quick answer! We've swapped all the variables and it works like a charm!
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))

5 Comments

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.
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.
Correct, this is why it is the second way, but I will add that this is unsafe and not recommended.
Or just remove it entirely ;-)
Here's an example string you can input to see the severity here: charmander.index(eval('__import__("os").system("echo I wiped your harddrive")')).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.