Defined Functions – Python

Currently my apps pretty much have a single main body in which all the data is collected, processed, and displayed/saved. A more Pythonic way of doing this is to get functions to do the work in a separate part of the application. In the main body I can then ask these functions to crunch some data I pass to it, and then receive a result back. At first this makes my code look a bit longer, but it should make it easier to debug in future as each defined function can be troubleshooted separately.

Let’s take a look at a very simple defined function:

>>> def square(x):
	x*=x
	return x

A function is defined named square. It accepts one argument. Whatever argument is passed to the function is squared, and the result passed back. I can now call square from the main body of the app and pass it my argument and I should get the square of that argument back:

>>> square(10)
100

If I have a variable with a value, I can pass the variable:

>>> a = 50
>>> square(a)
2500

It’s hard to see the benefits when I have a small app like above, but it makes a lot of sense in a much bigger app. I’ve now updated my OSPF Checker app to use definitions instead. The following is a few examples of the code:

def getip(i):
    ip = re.findall(r'Internet Address (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',i)
    return ip

def getarea(i):
    area = re.findall(r'Area ([\s]{0,3}[0-9]{1,5})',i)
    return area

for i in ospf:
    ip = getip(i)
    area = getarea(i)

Each definition can now be changed as a separate ‘app’ – A great example is when I ran my script on an LNS box with virtual-access interfaces. The getip function didn’t take into account the slightly different output:

Virtual-Access111 is up, line protocol is up
  Interface is unnumbered. Using address of Loopback56146 (10.9.0.250), Area 0, Attached via Network Statement

I can go in and just change the getip function:

def getip(i):
    ip = re.findall(r'Internet Address (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',i)
    if not ip:
        ip = re.findall(r'Interface is unnumbered. Using address of Loopback[0-9]{0,5}',i)
    return ip

App now picks up those sorts of interfaces just fine:

Int:	Virtual-Access266 
IP:	Interface is unnumbered. Using address of Loopback78437
Area:	0
Type:	POINT_TO_POINT
Cost:	1
Hello:	10
Dead:	40

© 2009-2020 Darren O'Connor All Rights Reserved -- Copyright notice by Blog Copyright