Python: Using vars() to assign a string to a variable

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

Leave a Comment