
Recall first from bytes vs str, references and the GIL
- str holds Unicode code points and bytes holds raw octets; never mix them without an explicit encode or decode.
- The GIL serialises Python bytecode, so CPU-bound work needs multiprocessing or C, while I/O-bound work suits threads or asyncio.
- Names are references, not values: b = a aliases one object, copy.copy is shallow and copy.deepcopy recurses.
Why code is split into modules and packages
2 min readIn the previous lesson you wrote scripts and functions inside one file. This lesson answers how to split that file into modules and packages, and how import finds them.
In the previous lesson you wrote scripts and functions inside one file. That works until the file grows to hundreds of lines, or until a second script needs the same function. Copying the function into two places is the trap to avoid: the two copies drift apart, a bug is fixed in one and not the other, and now you maintain the same logic twice.
Python's answer has three levels. A a single .py file that Python can execute and import, whose top-level names form its own namespace is one file, and you already use modules without noticing: every .py file is a module. A a directory that groups modules and subpackages under one dotted name, so related code ships and imports together is a directory of modules. And an the statement that loads a module or package, executes its top-level code once, and binds its namespace to a name in your program statement is the door into both.
The dotted name is the map. In devkit.flash, devkit is a package and flash is a module inside it. In devkit.util.crc, util is a subpackage and crc a module inside that. Dots mean "inside", and they let a hundred modules live in one place without their names colliding.
For embedded tooling this is not a nicety, it is the difference between a folder of disposable scripts and a toolbox. A team building SensorNode boards ends up with the same pieces in every script: a function to find the USB serial port, a function to parse a boot log, a function to flash an image. Put those in a package, install it once, and every script imports them instead of pasting them. The package becomes the one place where the flashing logic lives, so a fix to it reaches every tool that uses it.
The import statement and the module search order
4 min readThere are several import forms, and each binds a different name.
import devkit.flash # binds the name devkit, not devkit.flash
from devkit.flash import write_image # binds write_image directly
from devkit import flash # binds flash
import devkit.flash as f # binds the alias f
from devkit.flash import * # imports public names, see the next section
Note the first form carefully: import devkit.flash binds devkit, so you call devkit.flash.write_image(...). To reach the module with its short name you write from devkit import flash. All of these execute the module's top-level code exactly once, no matter which form you use or how many times you import it.
When you run an import, Python follows a fixed sequence. It first checks the the list of directory and archive paths that Python searches, in order, to find a module named in an import cache, then the built-in modules, then walks the directories in sys.path. This is the search order, and it is the first place to look when an import fails or resolves to the wrong file.
python3 -c "import sys; print(sys.path)"
# typical output: ['', '/usr/lib/python312.zip', '/usr/lib/python3.12',
# '/usr/lib/python3.12/lib-dynload', '/home/learner/.local/lib/python3.12/site-packages',
# '/usr/local/lib/python3.12/dist-packages', '/usr/lib/python3/dist-packages']
The output above is typical for Ubuntu 24.04; yours will differ in the exact paths. The important fact is the first entry. When you run python3 tool.py, sys.path[0] is the directory that contains tool.py. When you run python3 -m devkit or work in the interactive prompt, sys.path[0] is the empty string, which means the current working directory. This single difference decides whether import devkit finds the copy in your project or the copy installed in site-packages, and it is behind the classic "it imports the wrong version" bug.
The import system also caches. The first time a module is imported, Python executes its top-level code and stores the module object in sys.modules, a dictionary keyed by module name. Every later import of the same name returns the cached object without re-executing the code. That is why a module's top-level statements run only once, and why editing a module and importing it again in the same process does not reload it.
Check sys.modules: if the name is already imported, return the cached module object.
Check built-ins: a small set such as sys and builtins is searched before any file.
Walk sys.path in order: each directory and zip archive is searched for a match.
Find a file or package: a
.pyfile, a directory with__init__.py, or a compiled extension.Execute and cache: run the top-level code, put the module in sys.modules, bind the name.
Going deeperInside the finders and loaders
The import machinery is not one loop but a chain of finders held in sys.meta_path. The two you always meet are BuiltinImporter, which serves the built-in modules, and PathFinder, which walks sys.path. A finder returns a spec, and a loader executes the code from that spec. When PathFinder meets a directory it delegates to a FileFinder that knows the extensions: it can load a source file, a cached bytecode file, or a compiled extension module such as a .so on Linux or a .pyd on Windows. This is why a C extension and a pure-Python module are imported with the same import statement, and why zipimport can import straight from a .zip on sys.path. The bytecode cache you saw in the previous lesson, __pycache__/*.pyc, is how FileFinder skips recompiling a module whose source has not changed. If an import fails, the error message tells you the chain it walked: ModuleNotFoundError: No module named 'devkit' means the name was in neither sys.modules, the built-ins, nor any directory on sys.path.
Packages, __init__.py, and the public API
4 min readA regular package is a directory containing an __init__.py file. The file can be empty, and for the smallest packages that is enough: the folder is now importable, and its submodules are reached by dotted name. But __init__.py is also code, and it runs once, when the package is first imported. That makes it the natural place to set up the package's public face.
A a package with no init.py, whose portions can live in several directories on sys.path and merge into one dotted name is the alternative. Because it has no __init__.py, it has no code of its own and no single directory; it simply merges every directory named devkit that appears on sys.path. Namespace packages matter when you deliberately want one package name to be assembled from several projects, which is how plugin systems let other packages drop new subpackages into your namespace. For the normal case, one team and one repository, write the __init__.py and keep the regular package.
The two import styles inside a package are worth separating early. An absolute import names the full path from the top: import devkit.serial or from devkit.serial import open_port. A relative import starts with a dot and is resolved against the current module: from . import serial (a sibling module), from .serial import open_port, or from .. import util (one level up). Relative imports only work when the module knows it is inside a package, a fact that becomes important in the next section.
__init__.py lets you control the public surface. Suppose the team wants callers to write from devkit import write_image rather than from devkit.flash import write_image. You re-export the name:
# devkit/__init__.py
"""Flash, provision and test tooling for SensorNode boards."""
from .flash import write_image
from .serial import open_port
__all__ = ["write_image", "open_port"]
The __all__ list does two jobs. It is the list of names that from devkit import * imports, and it doubles as documentation of the package's intended public API. Everything not listed is still reachable by its full dotted name, but __all__ tells a reader and a linter which names are the stable contract.
When a package grows past a few modules, the __init__.py should stay thin. Its job is to re-export a small number of names and set __all__, not to contain logic. Keep the real code in leaf modules, keep each module importing its siblings with relative imports (from . import serial), and re-export only what callers should rely on. Inside the package, modules may import each other freely by relative name; outside the package, callers should reach in through the public names in __init__.py. A subpackage is just a nested directory with its own __init__.py, and the same rules apply at each level. This keeps the dependency direction one-way and makes the package cheap to test, because each leaf module can be imported on its own. The failure mode this avoids is a tangle where every module imports every other, so nothing can be tested or reused in isolation.
Key takeaways
- A module is one .py file and a package is a directory of modules; both are reached through the import system.
- import searches sys.path in order and caches results in sys.modules, and sys.path[0] depends on how you launched the program.
- __init__.py turns a directory into a regular package and, through re-exports and __all__, defines the public API; a namespace package has no __init__.py and can span several directories.
- Inside a package, an absolute import names the full dotted path, while a relative import starts with a dot and resolves against the current module.
Reflect
- Explain to a colleague, in two sentences: explain the roles of modules, packages and entry points, and state why a tool is split into them.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.