⚡ IT Wisdom A man walks into a server room and immediately walks out. He was looking for the cloud.
Skilled Practitioner
4249 XP 1751 to Expert
Units
Whetting Your Appetite — Why Python for Networking? Using the Python Interpreter An Informal Introduction to Python — Network Basics Control Flow — Making Decisions in Network Scripts Data Structures — Modeling Network Inventories Modules — Organizing Your Network Scripts Input and Output — Reading and Writing Network Data Errors and Exceptions — Building Reliable Network Scripts Classes — Modeling Network Devices as Objects Standard Library Part I — Tools Every Network Script Needs Standard Library Part II — Logging, Formatting, and Counting Virtual Environments and Packages — Isolating Your Dependencies Capstone — Build a Network Inventory Tool

What Is a Module?

A module is a Python file you can import into another script. It lets you split your code into reusable pieces instead of writing everything in one long file.

You have already used a module — sys in Unit 2. Python ships with hundreds of built-in modules. You can also write your own.


Importing Built-in Modules

import os
import sys
import json
import re

Once imported, you access the module's functions with a dot:

import os

print(os.getcwd())          # current working directory
print(os.path.exists("devices.txt"))  # does this file exist?

Import just what you need with from ... import:

from os.path import exists, basename

print(exists("devices.txt"))
print(basename("/home/emmy/scripts/check.py"))  # check.py

Creating Your Own Module

Any .py file is a module. Create device_utils.py:

# device_utils.py

def format_hostname(name):
    return name.strip().lower()

def get_device_type(hostname):
    if hostname.startswith("sw"):
        return "switch"
    elif hostname.startswith("rtr"):
        return "router"
    elif hostname.startswith("fw"):
        return "firewall"
    else:
        return "unknown"

Import it in another script in the same directory:

import device_utils

print(device_utils.format_hostname("  SW-CORE-01  "))
print(device_utils.get_device_type("rtr-edge-01"))

Output:

sw-core-01
router

Exploring a Module with dir()

dir() lists everything available in a module. Useful when you want to know what tools a module has:

import json
print(dir(json))

To filter out private internals (names starting with _):

public = [x for x in dir(json) if not x.startswith("_")]
print(public)

Check if a specific function is in a module:

import os
print("getcwd" in dir(os))   # True
print("path" in dir(os))     # True

Running a Module as a Script

Sometimes you want a module to do something when run directly but behave as a normal import when used by another script. Use __name__:

# device_utils.py

def format_hostname(name):
    return name.strip().lower()

if __name__ == "__main__":
    # This block only runs when the file is executed directly
    print(format_hostname("  SW-CORE-01  "))

When you run python3 device_utils.py — the block runs. When another script imports it — the block is skipped.


Summary

  • A module is any .py file — import it with import module_name
  • Built-in modules like os, sys, json, re give you powerful tools with zero setup
  • Your own modules let you share functions across multiple scripts
  • from module import func imports just one function — no need to prefix it with the module name
  • dir(module) shows everything a module contains
  • if __name__ == "__main__" lets a file work both as a module and a standalone script