Python Master Course V2 — 064. Packages and Import Paths
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 — MODULES AND PACKAGES · LESSON 064 / 200
Packages and Import Paths
Estimated study: 60–90 minutes. Prerequisites: functions, collections, control flow and the preceding lesson. Level: intermediate Python.
Video lesson
Video not yet available. Reserved for a verified video URL/player; written learning materials are available now.
Learning outcomes
Understand package layout and import resolution. After completing this lesson, you should be able to explain the underlying mechanism, run the example, identify a boundary case, and apply the concept in a practical program.
Understand Packages and Import Paths
A package gives related modules a shared namespace
A module is usually one Python source file. A regular package is a directory containing an __init__.py file and related modules. The package name groups those modules, so an import such as expensekit.totals says both which project owns the code and which part provides it. Namespace packages are another supported form, but this lesson uses ordinary packages with explicit initialization files to keep the first layout easy to understand.
Create the following files in one new practice directory. The tree is a file layout, not Python code. Leave __init__.py empty for now: a package does not need initialization side effects. Put the calculation in totals.py and the demonstration in __main__.py. Keeping those jobs separate allows another program to import the calculation without automatically printing a demonstration.
practice/
expensekit/
__init__.py
totals.py
__main__.py
def total_cents(amounts):
total = 0
for amount in amounts:
if type(amount) is not int or amount < 0:
raise ValueError("amounts must be nonnegative integer cents")
total += amount
return total
from .totals import total_cents
print(total_cents([550, 225]))
python -m expensekit
775
Understand what the dot and -m mean
The leading dot in from .totals import total_cents means “use totals from this package”. An absolute import would be from expensekit.totals import total_cents. Both identify the same module here, but relative imports require package context. Running python expensekit/__main__.py treats that file as a direct script and can fail with an attempted-relative-import error. Running with -m expensekit asks Python to locate the package and run its __main__ module in the intended context.
For this uninstalled layout, run from the directory containing expensekit. Python’s import search path includes locations determined by how Python was started, the standard library and installed packages. It does not search every folder on the computer. The current working directory matters for this -m invocation; the package directory itself is not the correct parent location. Later, installing the project makes imports available through that environment without relying on the source folder being your working directory.
Diagnose import errors without path hacks
When an import fails, check the selected interpreter, package spelling, parent directory and filename before editing sys.path. A nearby file named json.py or a package with a dependency’s name can shadow the intended import. For a module that exposes a file location, inspect module.__file__ to see what was actually loaded. Avoid fixing one machine by hard-coding an absolute developer path into the source; that makes the project less portable.
Package initialization runs when that package is first imported in an interpreter process, and imported modules are normally cached. Keep __init__.py lightweight and avoid network requests, prompts or writes at import time. A fresh Python process is the simplest way to recheck a changed beginner example. Your completion check is concrete: the command prints 775, importing total_cents prints nothing, an empty list returns zero, and a negative amount raises the documented error. See the Python package tutorial for package import syntax.
Import-cache recap
This existing json/sys.modules example reviews import caching. Build and launch the actual expensekit package from the distinct files above to practise this lesson’s package concept.
Requires Python 3.10+. Save the example as lesson64.py and run python lesson64.py (or python3). If it writes a file, run it in a disposable practice directory.
import json
import sys
print(json.loads('{"ok": true}')['ok'])
print('json' in sys.modules)
Expected output:
True
True
Step-by-step walkthrough
Read each statement in execution order. Identify imported modules, assigned variables, functions and the result passed to print(). Compare the output with the expected output and then change one input. Explain why the behavior changed. When an exception occurs, read the final traceback line and inspect the call that produced it.
Extension example
Refactor the central calculation or operation into a named function with a docstring and type hints. Add a caller that invokes it twice with different inputs. Test both results with assertions; for file operations, also test that the expected file exists and clean up practice files afterward.
Guided project — Packages and Import Paths application
Organize a package with __init__.py and an entry point.
- Write a short requirements document specifying input data, output data and expected errors.
- Implement one focused function or module for the core behavior.
- Write a separate program entry point to collect or construct example input.
- Add validation and informative errors where appropriate.
- Test a normal case, a boundary case and an invalid case.
- Write a README showing how to run and test the program.
Acceptance criteria: clear behavior, no unexplained dependencies, reproducible execution and a documented result. The project is a guided assignment; its implementation must be completed and tested by the learner.
Common mistakes, debugging and best practices
- Importing a local file with the same name as a standard-library module, causing shadowing.
- Using broad exception handlers that conceal the real defect.
- Assuming a path or dependency exists on every computer.
- Mixing input/output and reusable business logic into one difficult-to-test function.
- Testing only the happy path rather than edge cases and failures.
Debugging procedure: reproduce the failure with the smallest input; read the traceback; verify assumptions and data types; change one thing; rerun the same test; add a regression test after the fix.
Practice and explained answers
Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.
1. Why is __init__.py included in this lesson’s package?
Need a hint?
This example deliberately uses the regular-package form.
Reveal answer and explanation
Answer and reasoning:
It identifies the directory as the regular package form used here and can contain initialization code. It may be empty. Namespace packages can omit it, but that is a different packaging mechanism.
2. What does the dot in from .totals import total_cents mean?
Reveal answer and explanation
Answer and reasoning:
It resolves totals relative to the current package. It does not mean the operating system’s current directory, and it needs package context supplied by an import or a suitable -m execution.
3. Which directory should contain the shell when running the uninstalled example?
Reveal answer and explanation
Answer and reasoning:
The practice directory, which contains expensekit. From there run python -m expensekit. Once a package is installed into the chosen environment, import resolution should not depend on this source-folder arrangement.
4. Why can direct execution of __main__.py fail?
Reveal answer and explanation
Answer and reasoning:
A file launched by path is treated as a script rather than as part of its package. Its relative import may have no known parent package. Use python -m expensekit, preserving package context.
5. How can you check whether a local module is shadowing a dependency?
Reveal answer and explanation
Answer and reasoning:
import json
print(json.__file__)
The output is an environment-dependent filesystem path. If it points to an unintended json.py in the project, rename that local file and restart Python. Do not assume the imported module came from the standard library solely from its name.
Mastery checkpoint and summary
Demonstrate the concept without copying, explain one failure mode, complete the guided project and write three independent tests. These are suggested mastery checks, not account-synchronized completion records.
Key takeaway: Understand package layout and import resolution. Apply it through clear contracts, thoughtful error handling, and repeatable testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.