0

I need to create a variable in runtime. How do I do this using python

ex:

for l in self.device.output.split("\n"):
    r1 = re.match("(?P<phy>(te|gi)+)", l.strip(), re.IGNORECASE) 
    if r1 is not None:
        s = l.split(' ')

Here s will be of form : ['GigabitEthernet4/0/1', '', '', 'unassigned', '\r']

I need to create a variable like this

s[0]_myqueue0 
s[0]_myqueue1

So that I can assign values to above myqueues later in the program

How do I do this?

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Ravi Uday
  • 1
  • 1

1 Answers1

0

I am not sure what you are trying todo, there are many ways to create names at runtime.

The easiest option is to use a dictionary and assign keys to functions or pieces of code that you want to run later:

code_map = dict()

# later on in your code

code_map[s[0]]['myqueue0'] = 'foo'

This will result in:

>>> print(code_map['GigabitEthernet4/0/1']['myqueue0'])
foo
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • For some reason the above isnt working: I get this error: File "monitor_qos.py", line 365, in initialize code_map['s[0]']['myqueue0'] = 'foo' KeyError: 's[0]' bash-3.2$ – Ravi Uday Feb 09 '15 at 12:43
  • Don't add quotes around the key. Have a look at the code. – Burhan Khalid Feb 09 '15 at 13:18
  • I am not sure what I am missing, but it still doesnt work: `for l in self.device.output.split("\n"): r1 = re.match("(?P(te|gi)+)", l.strip(), re.IGNORECASE) if r1 is not None: s = l.split(' ') self.ifaces.append(s[0]) self.code_map[s[0]]['myqueue0'] = 'foo' ` Traceback (most recent call last): File "monitor_qos.py", line 928, in if v.initialize(): File "monitor_qos.py", line 364, in initialize self.code_map[s[0]]['myqueue0'] = 'foo' KeyError: 'GigabitEthernet4/0/1' bash-3.2$ – Ravi Uday Feb 09 '15 at 17:17
  • just doing `code_map = dict()` and then `code_map[s[0]]['myqueue0'] = 'foo'` won't work, because then `code_map[s[0]]` won't point to anything. Then trying to assign to `code_map[s[0]]['myqueue0']` won't work. Maybe you could get it working if you used a defaultdict(dict)... – Kevin Feb 09 '15 at 20:00