[Tutor] Dynamically assign variable names to tuple objects

Hugo Arts hugo.yoshi at gmail.com
Tue Mar 1 19:47:34 CET 2011

On Tue, Mar 1, 2011 at 7:10 PM, Sean Carolan <scarolan at gmail.com> wrote:
> On Tue, Mar 1, 2011 at 11:55 AM, Sean Carolan <scarolan at gmail.com> wrote:
>> Maybe someone can help with this.  I have a function that takes a
>> single file as an argument and outputs a tuple with each line of the
>> file as a string element.  This is part of a script that is intended
>> to concatenate lines in files, and output them to a different file.
> Not sure if this is the "right" or best way to do this, but I ended up
> using vars() to assign my variable names, like so:
> import sys
> myfiles = tuple(sys.argv[1:])
> numfiles = len(myfiles)
> varlist = []
> def makeTuple(file):
>   6 lines:    outlist = [] ----------
> for i in range(numfiles):
>    varlist.append('tuple'+str(i))
>    vars()[varlist[i]] = makeTuple(myfiles[i])


As you can see in the documentation, you really shouldn't modify the
object returned by vars() or locals(). It might work in some cases for
some implementations of python, but it's actually an undefined
operation, which basically means that an implementation may do
anything it damn well pleases when you try to actually do it.

Really, you shouldn't be trying to dynamically add variables to the
namespace for each tuple, it's dangerous and can introduce all sorts
of hard-to-catch bugs. Instead, put all your tuples in a list, and
address them by index:

tuples = []
for file in myfiles:

now you can address your tuples by tuples[0], tuples[1] and so forth,
which is pretty much the same as tuple0, tuple1, etc. Even better,
since it's in a list we can also iterate over it now with a for loop,
isn't that great?

Note also how I'm iterating over the myfiles list, which means I don't
have to use the range() function together with indexing with i, which
is a lot more readable.


PS: There's even shorter ways to write this little script, but I won't
bother you with them. If you want to know, check the map function, and
list comprehensions.

More information about the Tutor mailing list