Network Automation Example - Namedtuple | zeroslash.io

Network Automation Example - Namedtuple

Submitted by zeroslash on Wed, 05/09/2018 - 01:08

Let's say we just grabbed the list of interfaces from a router along with its error count. As you can see here I used namedtuples with a list comprehension (lines 13-14). Then I moved on to sort the data by error field and then provide some order with the name field as well, for errors with the same value (line 15). The output looks good. This type of approach seems enough for now but may change or improve given new scenarios to cover in the future. 

There's also an example at the bottom showing how you can replace a value on one of the fields. I understand you wouldn't really do something like this with our example use case but I just wanted to show you that it can be done with namedtuples. First, I tried to look for an entry we can manipulate using filter() (line 22) and grabbed the index of that entry (lines 26-28). Then we can use _replace() to change a value from one of the fields on that index (line 33). Take note that we are not changing values in place. Tuples are immutable and namedtuples are no different. So we had to reassign the new namedtuple object back to the same index.

Code:

Output:

Interface(name='FastEthernet', number='1/1/1', error='11')
Interface(name='FastEthernet', number='1/0/1', error='23')
Interface(name='FastEthernet', number='2/1/0', error='42')
Interface(name='GigabitEthernet', number='5/1/0', error='46')
Interface(name='GigabitEthernet', number='4/0/0', error='89')
Interface(name='GigabitEthernet', number='4/1/0', error='142')
Interface(name='GigabitEthernet', number='3/2/0', error='142')
Interface(name='GigabitEthernet', number='0/2/0', error='142')
Interface(name='FastEthernet', number='3/3/1', error='781')
filter 1/1/1
[Interface(name='FastEthernet', number='1/1/1', error='11')]
find the index of interface number 1/1/1
replace it's error value
before:
Interface(name='FastEthernet', number='1/1/1', error='11')
after:
Interface(name='FastEthernet', number='1/1/1', error='20')