Creating variables from list and accessing globally

倖福魔咒の 提交于 2021-02-17 05:22:05

问题


I’m writing a program that pulls a list of departments from a database. I want to avoid hardcoding this since the list may change.

I want to create a variable for each department to populate questions into a GUI. The problem I have is that I can create variables from the database list using the vars() function. I’m then storing the list of variable names so I can reference them elsewhere in my program. As long as I do everything in the same def, there is no problem. But I don’t know how to reference the dynamically created variables in a separate function.

Since I won’t know the variable names ahead of time, I don’t know how to make them available in other functions.

deptList = ['deptartment 1', 'deptartment 2', 'deptartment 3', 'deptartment 4', 'deptartment4']

varList=[]

def createVariables():
    global varList    
    for i in range(len(deptList)):

        templst=deptList[i].replace(' ', '')
        varList.append(templst+'Questions')
        globals()['{}'.format(varList[i])] = []


def addInfo():
    global varList

    print('varlist',vars()[varList[1]]) #Keyerror



createVariables()
print(varList)
vars()[varList[1]].append('This is the new question')
print('varlist',vars()[varList[1]]) #Prints successfully

addInfo()

回答1:


Do not use dynamic variables here. It makes no sense, just use one of Python's built-in containers, like a dict.

But, the reason your code isn't working is because vars() returns locals() when called with no argument. From the docs:

vars([object]) Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

...

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

So really, you just want to use the dict object returned by globals(). But this should make you wonder, why not just leave the global name-space out of it, and rather, just use your own custom dict object? Read this related question.




回答2:


Thanks for the tips. I was able to write the code I needed with a dictionary. Being new to python, it took a little trial and error, but the solution was better than what I was originally trying to do.

Thanks for your help!



来源:https://stackoverflow.com/questions/48145435/creating-variables-from-list-and-accessing-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!