This post is part of an ongoing series - see all the posts below.
We have used functions throughout this series. Every time we wrote print(), len(), int(), type(), or input(), we were calling a function. We even added a short note back in Chapter 2 saying we would cover them properly later. That time has come.
Up to this point, our scripts have been written as one block of code that runs from top to bottom. That works fine for small examples, but as your scripts grow, you will quickly run into problems. You will find yourself copy-pasting the same lines of code in multiple places, or writing one long script that becomes hard to follow and even harder to debug. Functions solve both of these problems.
A function is a reusable block of code that does a specific job. You write it once, give it a name, and then you can use (or "call") it as many times as you want from anywhere in your script. Functions make your code shorter, easier to read, and easier to maintain. If you need to change how something works, you only change it in one place, the function, instead of hunting down every copy of the same code.
In this chapter, we will cover how to define your own functions, how to pass values into them using arguments, how to get values back out using return statements, and a few important concepts like default arguments and variable scope. We will wrap up with a practical networking example where we turn some of our earlier scripts into proper, reusable functions.
Defining Your Own Functions
To create your own function in Python, you use the def keyword, followed by the function name, parentheses, and a colon. The code that belongs to the function goes on the next line, indented.
def greet():
print("Hello, network engineer!")
This is the simplest possible function. It is called greet, it takes no inputs, and all it does is print a message. But just writing the function does not run it. To actually run the code inside, you need to call the function, which means writing its name followed by parentheses.
def greet():
print("Hello, network engineer!")
greet()
greet()
greet()
Hello, network engineer!
Hello, network engineer!
Hello, network engineer!
Notice that we wrote the function once, but called it three times. That is the whole point of functions, you write the logic in one place and reuse it as many times as you need.
Function Naming
Function names follow the same rules as variable names, lowercase with underscores between words (snake_case), and they should describe what the function does. Good function names are usually verbs, because functions do something.
- Good -
connect_to_device,get_interface_status,parse_output - Bad -
Device,Stuff,do_thing
A well-named function makes your code almost self-documenting. If you see get_interface_status(device) in a script, you already have a good idea of what it does without even looking at the code inside.
Calling a Function Before Defining It
One thing to be careful about, Python reads your script from top to bottom. If you try to call a function before it has been defined, you will get an error.
greet()
def greet():
print("Hello, network engineer!")
Output
NameError: name 'greet' is not defined
The fix is as simple as defining your functions at the top of your script (or at least before you call them). This is a common convention in Python, all the function definitions live near the top of the file, and the actual logic that uses them runs further down.
Passing Information In
A function that just prints a fixed message is not very useful. Most of the time, you want your function to do something with information you give it. That information is passed in through arguments, which go inside the parentheses when you call the function.
To accept an argument, you write a variable name inside the parentheses when you define the function. That variable is called a parameter.
def greet(name):
print(f"Hello, {name}!")
greet("Suresh")
greet("Alice")
Hello, Suresh!
Hello, Alice!
Here, name is the parameter, and "Suresh" and "Alice" are the arguments. The function takes whatever you pass in and uses it inside the function body.
The terms "argument" and "parameter" are often used interchangeably, and in casual conversation it does not really matter. But strictly speaking, a parameter is the variable name in the function definition, and an argument is the actual value you pass in when calling the function. Do not worry too much about the difference for now.
You can pass in any type of value, a string, a number, a list, a dictionary, even another function. Functions do not care about the type, they just take whatever you give them.
def show_device_info(hostname, ip):
print(f"Device: {hostname}")
print(f"IP: {ip}")
show_device_info("r1_lnd_dc", "192.168.1.1")
Device: r1_lnd_dc
IP: 192.168.1.1
This function takes two arguments, and you pass them in the same order as they were defined. We will look at more flexible ways to pass arguments later in the chapter.
Return Values
So far, our functions have only printed things to the screen. That is fine for simple examples, but most useful functions actually return a value, meaning they give you back a result that you can store in a variable, use in a calculation, or pass to another function.
To return a value from a function, you use the return keyword.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
8
When Python reaches the return statement, the function stops running, sends the value back to wherever it was called from, and the caller can do whatever it wants with that value. In this case, we stored it in a variable called result and then printed it.
You can also use the return value directly, without storing it in a variable first.
def add_numbers(a, b):
return a + b
print(add_numbers(5, 3))
8
Print vs Return
This is one of the most common things beginners get confused about, so it is worth slowing down. print() and return look similar, but they do completely different things.
print()displays something on the screen. That is it. The script keeps running, but you cannot use what was printed for anything else.returnsends a value back to the caller. The script can store it, use it in another calculation, or pass it to another function.
Here is the difference in action.
def add_with_print(a, b):
print(a + b)
def add_with_return(a, b):
return a + b
x = add_with_print(5, 3)
y = add_with_return(5, 3)
print(f"x is {x}")
print(f"y is {y}")
8
x is None
y is 8
The first function printed 8 to the screen, but it did not return anything, so x is None. The second function did not print anything on its own, but it returned 8, so y holds that value.
If a function is meant to produce a result that the rest of your code might use, return it. Only use print() when the purpose of the function is to display something to the user.
Returning Multiple Values
A function can return more than one value at the same time by separating them with commas. Python wraps them into a tuple, which is just an ordered collection of values, similar to a list but immutable. We will cover tuples properly later, but for now, you can think of it as a list-like structure.
def get_device_info():
hostname = "r1_lnd_dc"
ip = "192.168.1.1"
vendor = "cisco"
return hostname, ip, vendor
device_info = get_device_info()
print(device_info)
('r1_lnd_dc', '192.168.1.1', 'cisco')
If you want to grab each value into its own variable, you can unpack them by writing matching variable names on the left side of the equals sign.
def get_device_info():
return "r1_lnd_dc", "192.168.1.1", "cisco"
hostname, ip, vendor = get_device_info()
print(hostname)
print(ip)
print(vendor)
r1_lnd_dc
192.168.1.1
cisco
This is a clean way to return related pieces of information from a single function.
Returning Early
You do not have to wait until the end of the function to use return. As soon as Python hits a return statement, the function stops, regardless of how much code comes after it. This is useful when you want to exit a function early under certain conditions.
def check_device_status(status):
if status == "down":
return "Device is down, skip it"
return "Device is operational"
print(check_device_status("down"))
print(check_device_status("up"))
Device is down, skip it
Device is operational
If the status is "down", the first return runs and the function exits. The second return is never reached. If the status is anything else, the first return is skipped and the second one runs.
