0

I see unboundlocalerror at random times. Could you please point me how to fix this?

def find_switch_and_port_cis(wwn):
    with open('zones_list.txt') as fin:
        for line in islice(dropwhile(lambda L: wwn not in L, fin), 1, 15, 1):
            if 'connected interface' in line:
                interface = re.findall(':(\S+)', line)
            elif 'switch name' in line:
                switch_name = re.findall(':(\S+)', line)
        print(wwn, ' is connected to interface:' , interface[0], ' on switch:', switch_name[0])

find_switch_and_port_cis(wwn)

The code gives the expect output:

50:01:43:80:01:1b:42:f6  is connected to interface: fc2/17  on switch: c3-cs9513-02

After few runs but after few runs it throws:

UnboundLocalError: local variable 'interface' referenced before assignment
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
redpy
  • 143
  • 5
  • 1
    If your `for` loop has 0 iterations or you never enter the `if` clause, you cannot print the value of `interface` variable because it has never been declared. – alex Apr 25 '21 at 17:26
  • Does this answer your question? ["UnboundLocalError: local variable referenced before assignment" after an if statement](https://stackoverflow.com/questions/15367760/unboundlocalerror-local-variable-referenced-before-assignment-after-an-if-sta) – wjandrea Apr 25 '21 at 17:30
  • Does this answer your question? [How can a name be "unbound" in Python? What code can cause an \`UnboundLocalError\`?](https://stackoverflow.com/questions/22101836/how-can-a-name-be-unbound-in-python-what-code-can-cause-an-unboundlocalerror) – Karl Knechtel Feb 06 '23 at 13:04

0 Answers0