using a instance variable in python

669 views python
5

I'm using a public API to programmatically configure a network switch with the python language. I'm not very experienced with python and I'm seeking some assistance to refactor the following code:

def main():
    conf_port_channel('sw1.eos')
    conf_vlan('4094', 'sw1.eos')
    conf_trunk_group('sw1.eos')
    conf_spanning_tree('sw1.eos')
    conf_svi('sw1.eos', '10.0.0.1/30')
    conf_mlag_vlan('sw1.eos', '10.0.0.2')
    conf_mlag_interface('sw1.eos')

In the main method I'm passing the sw1.eos argument to numerous methods that then create an instance of a network node. Below is an example of one of the methods which creates the node instance.

def conf_trunk_group(sw):
    node = pyeapi.connect_to(sw).api('interfaces')
    node.configure(['interface Port-Channel 10', 'switchport trunk group mlagpeer'])

How can I refactor this code to use one instance of 'node' created in the main, in all subsequent method calls?

node = pyeapi.connect_to(sw)

answered question

Pass the node as an argument?

@MorganThrapp are suggesting create the instance in main and then pass it to the other methods? How would I define the the methods?

That is correct. Either that or create it in the first function and return it from that

1 Answer

8

The easiest way to do this is to create the node in the main function and pass it as an argument to each of the subsequent function.

For example:

def conf_trunk_group(node):    
    node.configure(['interface Port-Channel 10', 'switchport trunk group mlagpeer'])

def main():
    node = pyeapi.connect_to('sw1.eos').api('interfaces')
    conf_port_channel('sw1.eos')
    conf_vlan('4094', 'sw1.eos')
    conf_trunk_group(node)
    conf_spanning_tree('sw1.eos')
    conf_svi('sw1.eos', '10.0.0.1/30')
    conf_mlag_vlan('sw1.eos', '10.0.0.2')
    conf_mlag_interface('sw1.eos')

This answer assumes that you wrote all of the functions. If not, the only way to do this is through some magic that is probably not worth it. You would have to overwrite the constructor in pyeapi to return a static instance

posted this

Have an answer?

JD

Please login first before posting an answer.