Python Modules and the Standard Library

Python Modules and the Standard Library
Table of Contents

This post is part of an ongoing series - see all the posts below.

Python for Network Engineers

So far, everything we have written has used Python's core features, things like variables, loops, functions, and basic data types. That has been enough to write some genuinely useful scripts, but Python on its own can only take you so far. The real power comes when you start using modules, pre-written bits of code that add new capabilities to your scripts.

The best part is that Python comes with a huge collection of these modules built in, called the standard library. You do not need to install anything extra, they are already there, ready to use. There are modules for working with dates and times, generating random numbers, reading and writing files, parsing JSON and a lot more.

In this chapter, we will look at what modules are, how to use them in your scripts with the import statement, and we will play around with the random module as our main example. By the end of the chapter, you will know how to bring in any module from the standard library and use it in your own scripts.

In the upcoming chapters, we will go one step further and look at how to install and use external libraries. But for now, let's stick with what is already on your machine.

What is a Module?

A module is just a Python file (a .py file) that contains code, usually functions, classes and methods, that you can use in another script. When you write your own Python script, that file is technically also a module. You could write a function in one file and use it in another.

For now, just think of a module as a collection of ready-made tools that someone else has written and packaged up for you to use. Instead of writing your own function to generate a random number, you can use the random module. Instead of writing your own code to get the current date, you can use the datetime module. Each module focuses on a specific topic and gives you a set of functions and tools to work with that topic.

The Standard Library

The standard library is the collection of modules that come bundled with Python. When you install Python, you get all of these modules. You do not need to download or install anything extra, they are already there.

Some of the most useful modules in the standard library include:

  • random - for generating random numbers and making random choices
  • datetime - for working with dates and times
  • os - for interacting with the operating system (files, directories, environment variables)
  • json - for reading and writing JSON data
  • re - for working with regular expressions
  • ipaddress - for working with IP addresses and networks
  • csv - for reading and writing CSV files

There are dozens more, but these are some of the ones you will use most often in network automation. The full list is on the official Python documentation site, but you do not need to memorise any of it. You just need to know that when you want to do something, there is probably already a module for it in the standard library.

The import Statement

To use a module in your script, you need to tell Python that you want to use it. You do this with the import statement at the top of your script.

import random

That is it. Once you have imported a module, you can use anything inside it by writing the module name, a dot, and the name of the function or class you want to use.

import random

number = random.randint(1, 10)
print(number)
7

The output will be a different number each time you run the script because random.randint(1, 10) returns a random integer between 1 and 10. The dot syntax (random.randint) is how you say "from the random module, use randint." Whether something like this is technically called a function or a method depends on how the module is built internally, do not worry about that distinction for now. In practice, you do not need to know or care how a module works internally, you just use the interface it gives you. Call it the way the documentation shows, and it will work regardless of what is happening under the hood.

It is a convention to put all your import statements at the very top of your script, before any other code. This makes it easy to see at a glance what modules a script depends on.

Playing with the random Module

Let's spend a bit of time on the random module because it is a great way to get comfortable with how modules work. It has several useful functions, and we will look at the most common ones.

random.randint()

random.randint(a, b) returns a random integer between a and b, including both. So random.randint(1, 100) could give you any number from 1 to 100.

import random

for _ in range(5):
    print(random.randint(1, 100))
48
16
89
3
53

Notice the underscore in for _ in range(5). The underscore is a convention in Python for "I do not care about this variable, I just need the loop to run." Since we are not actually using the loop counter inside the loop, we use _ instead of giving it a real name.

random.choice()

random.choice() picks a random item from a list. This is handy when you have a set of options and want to randomly pick one.

import random

devices = ["r1_lnd_dc", "r2_lnd_dc", "r3_lnd_dc", "r4_lnd_dc"]
random_device = random.choice(devices)

print(f"Randomly picked: {random_device}")
Randomly picked: r3_lnd_dc

This is useful for things like testing scripts against a random subset of devices, or building lab generators that pick random VLANs, IPs, or hostnames.

random.shuffle()

random.shuffle() takes a list and shuffles it in place, meaning it changes the original list.

import random

devices = ["r1_lnd_dc", "r2_lnd_dc", "r3_lnd_dc", "r4_lnd_dc"]
random.shuffle(devices)

print(devices)
['r3_lnd_dc', 'r1_lnd_dc', 'r4_lnd_dc', 'r2_lnd_dc']

random.sample()

random.sample() picks multiple random items from a list, without repeating any of them. You tell it how many items you want. This is useful when you want to randomly pick a few devices to test against, without picking the same one twice.

import random

devices = ["r1_lnd_dc", "r2_lnd_dc", "r3_lnd_dc", "r4_lnd_dc", "r5_lnd_dc"]
sample = random.sample(devices, 3)

print(sample)
['r2_lnd_dc', 'r5_lnd_dc', 'r1_lnd_dc']

We could technically write our own code to generate random numbers or shuffle a list ourselves, it is not impossible. But this is exactly the benefit of modules, someone already solved this problem, tested it, and made it fast and reliable. Writing your own random number generator is actually a lot harder than it sounds if you want it to be genuinely random and not follow a predictable pattern. Instead of reinventing that wheel every time you need it, you import random and get all of it for free. This is the whole point of the standard library, and later, external libraries too, you get to focus on solving your actual problem instead of rebuilding basic tools from scratch (aka re-inventing the wheel)

Different Ways to Import

There are a few different ways to import things in Python, and you will see all of them in real code. They all work, but they have different trade-offs.

import module

This is what we have been using so far. You import the whole module, and use its functions with the dot syntax.

import random

print(random.randint(1, 10))

This is the most explicit form. When you read the code, you can immediately see that randint comes from the random module.

from module import function

If you only need one or two specific functions from a module, you can import them directly. Then you can use them without the module name in front.

from random import randint

print(randint(1, 10))

This is a bit shorter, and it works exactly the same. The main difference is readability. With import random, you can see at a glance that randint comes from the random module. With from random import randint, that context is only visible at the top of the file where the import lives. Both styles are common, and you will see them all the time in real code. Use whichever one feels clearer to you for the script you are writing.

import module as alias

You can also give the module a shorter name (an alias) when you import it. This is mainly used for modules with long names, or by convention for popular libraries.

import random as r

print(r.randint(1, 10))

You will see this pattern a lot with external libraries later, like import pandas as pd or import numpy as np. For most of your own code, stick with the first style (import module) unless there is a good reason to use an alias.

Importing Multiple Things

You can also import multiple things from the same module in one line.

from random import randint, choice, shuffle

print(randint(1, 10))
print(choice(["a", "b", "c"]))

This works the same as importing them one by one, just more compact.

A Few Other Useful Standard Library Modules

We will not cover these in detail here, but it is worth knowing that they exist so you know where to look when you need them.

datetime

For working with dates and times. Great for adding timestamps to log files or filenames.

from datetime import datetime

now = datetime.now()
print(now)
2026-06-22 21:51:05.500028

os

For interacting with the operating system. Useful for working with file paths, directories, and environment variables.

import os

current_dir = os.getcwd()
print(current_dir)
/home/suresh/projects/network-automation

json

For reading and writing JSON data, which is the format most APIs use. We will use this a lot when we get to API automation later in the series.

import json

data = {"hostname": "r1_lnd_dc", "ip": "192.168.1.1"}
json_string = json.dumps(data)

print(json_string)
{"hostname": "r1_lnd_dc", "ip": "192.168.1.1"}
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Packetswitch.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.