How do I combine instance+string for variable

Marc losnations at comcast.net
Fri Aug 1 19:51:56 EDT 2003


> >I have several instances of telnet connections that I label
> How do you "label" them? By assigning, like conn2 = someSourceOfConn(...)?

Exactly. They are each separate instances of a telnet connection:

conn2 = telnetlib...
...
conn8 = telnetlib...

> 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?

Actually right now I'm using the list method:

<snippett>
conns = [conn2, conn3, conn4, conn5, conn6, conn7, conn8]
...
for int in range(2,9):
    qput(key.command, conns[int-2], act_user("user-ID" + str(int), "CTAG",
"t*sting" + str(int) ) )
<end of snippett>

I didn't include the code originally because it goes off in a lot of
directions. I'm putting it into a queue with function qput that later gets
executed with a function in file key.

The list method works for me with a small number of connections, but if I
ever need a lot of connections it will be a little klunky. Therefore I was
trying to find a fix similar to using setattr if I was using classes. So
basically I want to be able to use the conn2 that I assigned before, but
referencing it using a string.

I think the method you mentioned:

     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)

is what I'm looking for as it appears to concatenate "conn" with a number to
create the instance name. I hadn't come across the built-in function "vars"
yet, but I was trying to accomplish the same thing using "eval".

Thanks for the tip,
Marc






More information about the Python-list mailing list