Python Modules and Packages
PCAP objective 1.5 is create and use user-defined modules and packages, and there is much less machinery than people expect: a module is a .py file, a package is a directory containing __init__.py, and being importable means being somewhere on sys.path. The examinable subtleties are that __init__.py runs when the package is imported, and that importing a package does not import its submodules.
Modules and Packages Guide 8 of 25 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 18 min
Since Python 3.3 a directory without __init__.py can still be imported as a namespace package. The exam expects __init__.py, and this guide uses it - but do not be surprised when a real project omits it.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the user-defined modules and packages objective. This matters because importing a package does not import its submodules - so an import that looks correct fails at the point of use.
- making a module, which is only a file
- adding the guard that stops the body running on import
- building a package, and importing from it four ways
- finding that importing a package does not import its submodules
- learning the three ways to make a module findable
Before you start
- guide 4 - the import forms and the search path.
- guide 4 - the
__pycache__behaviour appears again here.
-
A module is a file
-
The guard that stops the body running on import
-
Where the bytecode went
-
A package is a directory with __init__.py
-
Importing from a package
-
Importing a package does not import its submodules
-
The three ways to make a module findable
-
What the exam does with this objective