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!
To assign it to a variable, we can use the variable name and “=” operator. Normally single and double quotes are used to assign a string with a single line of character but triple quotes are used to assign a string with multi-lines of character. This is how to declare and assign a variable to a string in Python.
How to create a string and assign it to a variable. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable.
The var() function is part of the standard library in Python and is used to get an object's _dict_ attribute. The returned _dict_ attribute contains the changeable attributes of the object. This means that when we update the attribute list of an object, the var() function will return the updated dictionary.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
The pythonic way to create a sequence of variables
If you want a sequence of variables, create a sequence. Instead of trying to create independent variables like:
variable0 variable1 variable2 variable3
You should look at creating a list
. This is similar to what S.Lott is suggesting (S.Lott usually has good advice), but maps more neatly onto your for
loop:
sequence = [] for _ in xrange(10): sequence.append(function_that_returns_data())
(Notice that we discard the loop variable (_
). We're just trying to get 10 passes.)
Then your data will be available as:
sequence[0] sequence[1] sequence[2] sequence[3] [...] sequence[9]
As an added bonus, you can do:
for datum in sequence: process_data(datum)
At first, you may twitch at having your sequence start at 0. You can go through various contortions to have your actual data start at 1, but it's more pain than it's worth. I recommend just getting used to having zero-based lists. Everything is built around them, and they start to feel natural pretty quickly.
vars() and locals()
Now, to answer another part of your question. vars()
(or locals()
) provides low level access to variables created by python. Thus the following two lines are equivalent.
locals()['x'] = 4 x = 4
The scope of vars()['x']
is exactly the same as the scope of x
. One problem with locals()
(or vars()
) is that it will let you put stuff in the namespace that you can't get out of the namespace by normal means. So you can do something like this: locals()[4] = 'An integer'
, but you can't get that back out without using locals again, because the local namespace (as with all python namespaces) is only meant to hold strings.
>>> x = 5 >>> dir() ['__builtins__', '__doc__', '__name__', 'x'] >>> locals()[4] = 'An integer' >>> dir() [4, '__builtins__', '__doc__', '__name__', 'x'] >>> x 5 >>> 4 4 >>> locals()[4] 'An integer'
Note that 4 does not return the same thing as locals()[4]. This can lead to some unexpected, difficult to debug problems. This is one reason to avoid using locals()
. Another is that it's generally a lot of complication just to do things that python provides simpler, less error prone ways of doing (like creating a sequence of variables).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With