0

I have created several variables with different values. Then I have created a while to access them one at a time. I would like to know how to access the value of a variable created using a composition of the variable ([base_name] + count)?

For example:

instanceNumber=3
instance1="server1"
instance2="server2"
instance3="server3"

print instance1 --> This prints server1

count = 1
while count >= instanceNumber:
    instanceServer = 'instance' + str(count)
    print "%s" % instanceServer --> This prints only instance1
    # Execute some action on the server
    count += 1

I need to get server1, server2, server3 one after the other. I need to do this without using a list or a dictionary.

Thanks

radicaled
  • 2,369
  • 5
  • 30
  • 44
  • 1
    Generally speaking: you don't. Use a list instead: `instances = ['server1', 'server2', 'server3']`, so you can simply use `instances[0]`, `instances[1]` and `instances[2]`. – Martijn Pieters Jun 08 '17 at 17:08
  • "I need to do this without using a list or a dictionary." Why? – juanpa.arrivillaga Jun 08 '17 at 17:10
  • Well, the idea is how to get the variable value using a composition of variables. I will create the list or a dictionary. I was checking to use globals() or locals() – radicaled Jun 08 '17 at 17:14
  • 1
    Yes, you should use globals() in this case. instanceServer = globals()['instance' + str(count)] – Chris Koston Jun 08 '17 at 17:18
  • @ChrisKoston No, one *shouldn't* use `globals` in this case, one should just *use a container like a list or a dict*. – juanpa.arrivillaga Jun 08 '17 at 17:26
  • @radicaled Please take Martijn's advice. Don't use `locals` or `globals`, that is very bad design. – juanpa.arrivillaga Jun 08 '17 at 17:27
  • @juanpa.arrivillaga "I need to do this without using a list or a dictionary." – Chris Koston Jun 08 '17 at 17:39
  • @ChrisKoston so, if someone asks "I need to jump off a bridge. How do I get to the nearest bridge" you'll say "Right over there!" ? No, you should't encourage bad practices. There are a few valid situations to use `globals` and `locals` (e.g., you are writing a debugger), but this is *almost certainly not one of those cases*. – juanpa.arrivillaga Jun 08 '17 at 17:43
  • I have never used global or local. But I was having the same issue with another tool (HPOO) and I started to wonder how to do it in python. – radicaled Jun 08 '17 at 18:58
  • @juanpa.arrivillaga there is a "slight" difference between the severity of the consequences of jumping of a bridge and using globals() in ultra simple script for convenience. Also, if radicaled needs to do it without a list or dict he probably has a reason for that and indicates that he already knows the other solution. – Chris Koston Nov 06 '17 at 22:48

0 Answers0