KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I find it very useful to be able to create new variables during runtime and create a dictionary of the results for processing later, i.e. writing to a file: myDict = {} for i in range (1,10): temp = "variable"+str(i) vars()[temp] = myFunctionThatReturnsData() # variable1= data1, variable2 = data2,etc. myDict[temp] = vars(temp) which creates the dictionary entry [result1:data1] which i can call with myDict[result1]. I have been using vars() without really understanding what I'm doing. I take it vars() returns a dictionary with the local variables(?), and vars()[x] = y creates a new dictionary entry of [x:y] ? I have a script where I pass in a dictionary prepared with {input1:data1,input2:data2}, and i use this method to iterate through all the values, store all the results, and output it to a file. This bit of code is inside a function within a class, and is working. My source of confusion is that I have read various posts on how locals() shouldn't be messed with, and how vars() is equivalent(?) to locals(), or globals().. So my question is (at least) two-fold: 1.What exactly does vars(),or in particular, vars()[x] = y do, 2.What the scope of this dictionary is (what I need to keep in mind as I write bigger programs 3.Whether this is good programming practice. Thanks in advance!
Tags (comma-separated)
Save Edits
Cancel