From point A to point B
Point A: all your code lives in a single file that keeps growing, and every new script starts by copying functions from the last one. Point B: by the end of this chapter, you'll split your code into reusable modules and packages, and you'll understand where Python looks for what you import. You'll also install third-party libraries in a virtual environment.
What a module is
A long program gets hard to read and maintain. The solution is to split it into modules: units that group related code. A module is the logical organization; its physical form is a file. Every .py file is a module.
Create a file named inventory.py with this content:
"""Utilities for the network device inventory."""
DOMAIN = "lab.local"
def fqdn(hostname):
return f"{hostname}.{DOMAIN}"
class Device:
def __init__(self, hostname):
print("a Device was created")
self.hostname = hostname
print("loading the inventory module")
To use it from another program, you import it with import and the file name without the extension. Create program.py in the same folder:
import inventory
print(inventory.fqdn("r1"))
print(inventory.DOMAIN)
$ python3.14 program.py
loading the inventory module
r1.lab.local
lab.local
Look at the first line of the output. import doesn't just make what the module defines available to you: it also runs its code from top to bottom. That's why the module's print shows up. On the other hand, "a Device was created" doesn't appear: the module defines the class, but nobody creates an object with it.
The module only runs the first time you import it. If you import it again, Python reuses the one it already loaded. You'll also see a __pycache__ folder: Python stores the already compiled code there so it loads faster next time.
Ways to import: import, from and as
A single import statement can load several modules separated by commas. Here you load 3 from the standard library: os (the operating system), sys (the interpreter itself) and time (dates and times). Even so, the PEP 8 style guide recommends one import per line.
import os, sys, time
print(time.strftime("%Y") >= "2025") # → True
print(os.sep, sys.version_info >= (3, 14)) # → / True
To use something from a module, you write the module name in front of it: time.strftime. That prefix is its namespace. It prevents clashes: if two modules define a connect function, each one keeps its prefix and they don't step on each other.
With from ... import, you bring specific names into the current namespace and skip the prefix. With as, you give them an alias:
from inventory import fqdn, DOMAIN
from time import asctime as now
import ipaddress as ipa
print(fqdn("fw01"))
print(DOMAIN)
print(type(now()))
print(ipa.ip_network("10.0.0.0/30").num_addresses)
$ python3.14 from_import.py
loading the inventory module
fw01.lab.local
lab.local
<class 'str'>
4
There's also from module import *, which brings in every public name. It's considered bad practice: you don't know which names arrive, and one of them can silently overwrite yours. A module can limit what * exports with a list called __all__.
Where Python looks: sys.path and PYTHONPATH
inventory.py had to sit next to program.py. So why does import os work without an os.py in your folder? Because Python looks for modules in a list of directories stored in sys.path, in order:
import sys
for path in sys.path:
print(path)
$ python3.14 show_path.py
/path/to/project
/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python314.zip
/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python3.14
/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python3.14/lib-dynload
/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python3.14/site-packages
On your machine, the paths will differ, but the order is the same:
- The folder of the script you run. That's why it found
inventory.py. - The folders in the
PYTHONPATHenvironment variable, if you set it. - The standard library, where
os,sysandtimelive. site-packages, where third-party libraries get installed.
PYTHONPATH adds your folders right after the script's folder:
$ PYTHONPATH=/opt/my_modules python3.14 show_path.py
/path/to/project
/opt/my_modules
/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python314.zip
…
If Python goes through the whole list and doesn't find the module, it raises ModuleNotFoundError, a subclass of ImportError:
try:
import netmiko_missing
except ModuleNotFoundError as e:
print(type(e).__name__, "→", e)
print(issubclass(ModuleNotFoundError, ImportError))
# → ModuleNotFoundError → No module named 'netmiko_missing'
# → True
A common mistake is naming your file the same as an existing module, like json.py or socket.py. Since the script's folder comes first, Python imports your file instead of the original.
PYTHONPATH directory to make them available system-wide. Today, the recommended approach is to turn them into an installable package and use virtual environments (you'll see them at the end). Also, ModuleNotFoundError has existed since Python 3.6, and since 3.11 the -P option (or PYTHONSAFEPATH) keeps the script's folder out of sys.path.Modules are objects: __name__ and __doc__
In Python, everything is an object, and modules are no exception: they're of type module and they have attributes.
import inventory
import inventory # the second time, it doesn't run again
print(inventory.fqdn("sw1"))
print(type(inventory))
print(inventory.__name__)
print(inventory.__doc__)
$ python3.14 program2.py
loading the inventory module
sw1.lab.local
<class 'module'>
inventory
Utilities for the network device inventory.
__doc__ holds the module's docstring: the string that appears as the first statement in the file. If there isn't one, it's None.
__name__ holds the module's name when you import it. But when you run the file directly, it's "__main__". With that, you can write a file that works as a library and as a script at the same time:
"""Reusable module that can also run as a script."""
def is_private(ip):
import ipaddress
return ipaddress.ip_address(ip).is_private
print("This line always shows")
if __name__ == "__main__":
print("Run as a program")
print(is_private("10.1.1.1"), is_private("8.8.8.8"))
$ python3.14 ping_util.py
This line always shows
Run as a program
True False
If another file does import ping_util, it will only see "This line always shows": the if block doesn't run, and ping_util.__name__ is "ping_util". It's the ideal place for quick tests or for a tool's entry point.
Packages and __init__.py
If modules organize code, packages organize modules. A package is a special kind of module that contains other modules. Its physical form is a folder. In an automation project, you could have one package for vendors, another for inventories and another for reports.
A folder becomes a regular package when it contains an __init__.py file. It's usually empty, although it can define shared items, such as a constant. Python runs it when you import the package.
project/
├── use_package.py
└── net/
├── __init__.py ← SSH_PORT = 22
└── devices/
├── __init__.py ← empty
├── cisco.py
└── juniper.py
To import, you separate packages, subpackages and modules with dots:
# net/__init__.py
"""Network utilities package."""
SSH_PORT = 22
# net/devices/cisco.py
def vlan_command(vlan, name):
return f"vlan {vlan}\n name {name}"
# net/devices/juniper.py
from . import cisco # relative import: same package
from .. import SSH_PORT # goes up one level, to the net package
def vlan_command(vlan, name):
return f"set vlans {name} vlan-id {vlan}"
def port():
return SSH_PORT
And from use_package.py:
import net.devices.cisco
print(net.devices.cisco.vlan_command(10, "USERS"))
from net.devices import juniper
print(juniper.vlan_command(10, "USERS"))
print(juniper.port())
import net
print(net.SSH_PORT, net.__doc__)
$ python3.14 use_package.py
vlan 10
name USERS
set vlans USERS vlan-id 10
22
22 Network utilities package.
Inside a package, one dot in from . import means "this package" and two dots mean "the parent package". These are relative imports, and they only work inside a package. Outside it, always use the full path.
Namespace packages
Since Python 3.3 (PEP 420), a folder without __init__.py can also be imported. It's a namespace package, and it has a special property: its content can be spread across several folders.
ns_a/plugins/syslog.py ← NAME = "syslog"
ns_b/plugins/snmp.py ← NAME = "snmp"
import sys
sys.path[:0] = ["ns_a", "ns_b"]
import plugins
from plugins import syslog, snmp
print(syslog.NAME, snmp.NAME)
print(plugins.__file__)
print(len(plugins.__path__))
$ python3.14 namespace.py
syslog snmp
None
2
The two plugins folders combine into a single package, with 2 paths in __path__ and no file of its own. That way, several separately installed libraries can contribute modules to the same package. For your own code, the recommendation is still to include __init__.py: it makes clear what's a package and avoids surprises.
Third-party libraries: pip and venv
The standard library covers a lot, but to automate networks you'll use external libraries: HTTP clients for REST APIs, SSH connections or configuration parsing. They're published on PyPI (the Python Package Index) and installed with pip.
Before you install anything, create a virtual environment with venv. It's a folder with its own site-packages, isolated from the rest of the system. Each project gets its own libraries and versions, with no conflicts between them.
$ python3.14 -m venv .venv
$ source .venv/bin/activate
(.venv) $ python -m pip install requests
(.venv) $ python -m pip list
Package Version
------------------ ----------
certifi 2026.10.23
charset-normalizer 3.5.2
idna 3.20
pip 26.1.2
requests 2.34.2
urllib3 2.8.0
(.venv) $ python -m pip freeze > requirements.txt
(.venv) $ deactivate
- On Windows, you activate it with
.venv\Scripts\activate.bat(cmd) or.venv\Scripts\Activate.ps1(PowerShell). python -m pipguarantees that you use the active interpreter's pip, not another one.pip freezesaves the exact versions; someone else reproduces them withpip install -r requirements.txt.- The environment is disposable: don't commit it to Git, and recreate it when you need it. Since Python 3.13,
venvcreates a.gitignoreinside it that excludes it.
The versions in the list are the ones installed when this chapter was written; you'll see the current ones.
venv nor a bundled pip existed. venv arrived in Python 3.3 (PEP 405), and ensurepip, which installs pip alongside Python, in 3.4 (PEP 453). Today they're the basic workflow of any project.Challenge
Answer before you open the solution.
1. You import a module that has a stray print at the end. Does it run?
Yes, the first time you import it. import runs all the module's code; later imports reuse the module that's already loaded.
2. What is if __name__ == "__main__": for?
To run code only when you launch the file directly. When it's imported, __name__ holds the module name and that block is skipped.
3. You create json.py to test something, and suddenly import json fails in another script in the same folder. Why?
Because the script's folder comes first in sys.path. Python imports your json.py instead of the standard module. Rename your file.
4. What sets a regular package apart from a namespace package?
The regular one has __init__.py; the namespace one doesn't. A namespace package can be spread across several sys.path folders.
5. Two projects need different versions of the same library. What do you do?
One virtual environment per project. With python3.14 -m venv .venv, each one gets its own site-packages.
Key takeaways
- Every
.pyfile is a module;importloads it and runs its code only once. import modulekeeps the namespace;from module import namebrings it into the current one;ascreates aliases. Avoidimport *.- Python searches
sys.path: the script's folder,PYTHONPATH, the standard library andsite-packages. if __name__ == "__main__":separates use as a script from use as a library.- A package is a folder of modules; with
__init__.pyit's regular and, without it, a namespace package. - Install libraries with
python -m pipinside a virtual environment created withvenv.
In the next chapter, you'll read and write files: real configurations, inventories and logs.
Official resources
- Modules (tutorial)docs.python.org
- The import systemdocs.python.org
- The initialization of the sys.path module search pathdocs.python.org
- venv: creation of virtual environmentsdocs.python.org
- PEP 420: Implicit namespace packagespeps.python.org
- Install packages in a virtual environment using pip and venvpackaging.python.org
Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.