1

I am looking for a way to convert a string into an existing variable name of a list, I am a beginner in this field and trying to develop a simple program and I encounter this kind of a problem I have, to summarize, I need to pass a parameter to function which is a string, and to that said function I need that parameter to be converted as a variable name so I can access the lists that has the same name as that string.

this is my code:

#datachart.py
datos = [0,100,100] #I need to access this and print it to another script


#main.py
from datachart import *

def data_send(usr):
    #Now the user input which is a string is now here as 'usr'
    #The problem is here, I cant access the lists from datachart cause 
    #using usr[0] will just take the character of a string.

    #somecode or something to turn usr into a recognizable variable name 
    #of a list from datachart which is named as datos to be able to do 
    #the code below:

    print("Coins: {} Tokens: {} Money: {}".format(usr[0],usr[1],usr[2]))

def send_val():
    usr = input("Username: ")

    # Consider "datos" as the value of user input.

    data_send(usr)

send_val()

4 Answers 4

2

You can assign the list in datachart.py to the variable input in the main.py:

#datachart.py
datos = [0,100,100]

#main.py
from datachart import *

def data_send(usr):
    usr = datos        # assigned here
    print("Coins: {} Tokens: {} Money: {}".format(usr[0],usr[1],usr[2]))

def send_val():
    usr = input("Username: ")
    data_send(usr)

send_val()

EDIT:

Another way could be using getattr():

From the docs:

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

#datachart.py
datos = [0,100,100]

#main.py
from datachart import *
import datachart

def data_send(usr):
    usr = getattr(datachart, usr, None)   # with None as a default val
    if usr:
       print("Coins: {} Tokens: {} Money: {}".format(usr[0],usr[1],usr[2]))

def send_val():
    usr = input("Username: ")
    data_send(usr)

send_val()

OUTPUT:

Username: datos
Coins: 0 Tokens: 100 Money: 100

Note: I recommend the edited version

Sign up to request clarification or add additional context in comments.

3 Comments

This works fine and really efficient, but what if I have more than one list in datachart.py not just datos. for example: #datachart.py datos = [0,100,100] datos2 = [100,50,34] datos3 = [32,100,233] Is there any way to specifically call these lists on data_send? or its ideal to just use dictionary if it that somehow works.
@Sorcuris you could check with the user input in your send_val() method, then pass that string input to getattr() method and if it exists in the datacharts.py it would return the list.
It works fine, might use the getatt for another functions which is appending values to an specific list.
2

You can certainly do that using the globals() builtin method.

# file1
datos = [0,100,100]
from file1 import *

print(dict(globals())['datos'])

globals() Returns a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

Read more in the docs

Comments

1

In python 2 I find your code to be working fine

In python 3, since input is converted to string instead of accessing variables inside the code, you need to use globals() to access back variable list.

Note that, this is only for the purpose of exercising, using a dict instead of accessing variable directly is prefered, because such behavior is unsafe from a security standpoint.

def data_send(usr):
    try:
        usr = globals()[usr]
    except KeyError:
        return # Handle case the user inputs a non-existing variable the best you can
    print("Coins: {} Tokens: {} Money: {}".format(usr[0],usr[1],usr[2]))

Comments

-2

Python dictionaries would be suitable for this use case. Essentially all possible parameter values would become keys in the dictionary chart_data.

chart_data = {
   "dataos": [0,100,100]
}

#main.py
from datachart import *

def data_send(usr):
    print("Coins: {} Tokens: {} Money: {}".format(chart_data[usr][0],chart_data[usr][1],chart_data[usr][2]))

def send_val():
    usr = input("Username: ")
    data_send(usr)

send_val()

2 Comments

Not really, you changed the list to a dict, not sure if that is acceptable.
@DirtyBit leave that to the the person who asked the question to decide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.