user2501498
user2501498

Reputation: 65

How can I use the command vars()[x] into a function?

What I'm trying to do is a little longer than the following example, but anyways, it doesn't work and I have no idea how to figure out. I need to use the variables like strain1, strain2 to be assigned with arrays, but first of all, I'm trying to assign an empty list []. If I don't use a function, that works. I need to use the block several times tho, that's why I need this function.

def test():
    for i in xrange(11):
         v = 'strain' + '%d' % i
         vars()[v] = []

test()
strain5

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    strain5
NameError: name 'strain5' is not defined

Upvotes: 0

Views: 46

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124070

You are looking for the globals() function instead.

vars() (without arguments) returns the current namespace, in a function that is the local namespace, not the module globals.

Demo:

>>> def test():
...     for i in xrange(11):
...          v = 'strain' + '%d' % i
...          globals()[v] = []
... 
>>> test()
>>> strain5
[]

However, you want to rethink your variables. Invariably, you really want to create a list or dictionary instead:

strains = [[] for _ in xrange(11)]

creates 11 nested lists, which you access with strains[0], strains[1], etc.

Upvotes: 4

Related Questions