Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list of variables to strings [duplicate]

Tags:

python

I have a list of commands that I want to iterate over so I've put those commands into a list. However, I want to also use that list as strings to name some files. How do I convert variable names to strings?

itemIDScore = """SELECT * from anytime;"""

queryList = [itemIDScore, accountScore, itemWithIssue, itemsPerService]
    for x in queryList:

    fileName = x+".txt"
    cur.execute(x) #This should execute the SQL command
    print fileName #This should return "itemIDScore.txt"

I want fileName to be "itemIDScore.txt" but itemIDScore in queryList is a SQL query that I'll use elsewhere. I need to name files after the name of the query.

Thanks!

like image 725
Publiccert Avatar asked Dec 07 '25 15:12

Publiccert


2 Answers

I don't think you may get name of the variable as string from the variable object. But instead, you may create the list of string of your variables as:

queryList = ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService']

Then you may access the value of variable from the variable name string using the globals() function as:

for x in queryList:
    fileName = "{}.txt".format(x)
    data = globals()[x]
    cur.execute(data) 

As the globals() document say:

Return 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).

like image 108
Moinuddin Quadri Avatar answered Dec 09 '25 06:12

Moinuddin Quadri


As far as I know, there is no easy way to do that, but you could simply use a dict with what currently are variable names as keys, e.g.:

queries = {
    'itemIDScore': 'sql 1', 
    'accountScore': 'sql 2',
    ...
}

for x in queries:
    fileName = x + ".txt"
    cur.execute(queries[x])
    print fileName

This would also preserve your desired semantics without making the code less readable.

like image 32
Vadim Landa Avatar answered Dec 09 '25 04:12

Vadim Landa