How do I combine instance+string for variable

Bengt Richter bokr at oz.net
Fri Aug 1 23:51:47 CEST 2003


On 1 Aug 2003 14:05:19 -0700, mnations at airmail.net (Marc) wrote:

>Hi all,
>
>I can't remember how to do this.
>
>I have several instances of telnet connections that I label
How do you "label" them? By assigning, like conn2 = someSourceOfConn(...)?

>conn2,conn3, etc. Later when I want to scroll through all of these I
>wanted to do something like this:
>
>    for int in range(2, 9):
         ^^^-- BAD name!! you are shadowing the builtin int.
>            use... conn+str(int) {I'm passing it into another
>function}
Do you want to pass a name in the form of a string, like 'conn2' or do you
want the conn2 that you assigned before?

<untested>
If you know the names, you could just write

     for aConn in (conn2, conn3, ..., conn8): # filling in the rest in place of '...'
         usingFunc(aConn)

If you had stored the conn's in a list instead of individual names, you could write

     for aConn in theList:
         usingFunc(aConn)

If you want to pick them up by generated string name from the local namespace, you could write
something like you started with, e.g.,

     for i in range(2, 9):
         name = 'conn%s' % i
         aConn = vars()[name]  # or use globals() in place of vars() if not in local namespace
         usingFunc(aConn)

or in one line
     for i in range(2, 9): usingFunc(vars()['conn%s'%i])  # ditto re globals() vs vars()

</untested>


>
>I can't get it to work. I've tried using setattr and eval, but nothing
>seems to work. Can I get a little help.

Post the code that creates the conn2 etc bindings if the above does not work for you.

Regards,
Bengt Richter




More information about the Python-list mailing list