Modules and Project Structure
Python Module Namespaces and PEP 328
BOTIE
PEP 328, created in 2003, addressed ambiguity between modules within a package and modules elsewhere on the import path. Absolute imports and explicit relative imports express different relationships. This was a documented development in Python's import rules, rather than an invention of modular programming.
Sources for this history
Importing a Helper Started the Whole Report
Botie moves a useful calculation into report.py. Another script imports it, and the import also opens the default file and prints a report. Reusing the helper now starts unrelated application work.
The module should expose behavior its callers need. Choosing inputs and deciding to run the application can remain explicit actions.
The rows describe a small Python module. These blocks inspect that description; the Python challenge separates reusable helpers from the application entry point.
Step 1 of 1
Keep entry-point work above the calculation
The command layer depends on a calculation; the calculation does not need to import the command layer.
| Module | Imports | Responsibility |
|---|---|---|
| cli | io, summary | Choose inputs and display output |
| io | csv | Read the file format |
| summary | statistics | Calculate from supplied values |
cli
- Imports
- io, summary
- Responsibility
- Choose inputs and display output
io
- Imports
- csv
- Responsibility
- Read the file format
summary
- Imports
- statistics
- Responsibility
- Calculate from supplied values
A module owns a namespace
Moving the file read does not help if another report action still runs during import. Both the kind of work and its current location matter.
Stop an import from running the report
Importing the report helper unexpectedly opens readings.csv. Ordinary function definitions belong at module scope, but reading a file and printing a report should wait until the application is run. Each row describes one step and when it currently happens.
BOTIE
Report-run steps currently performed during import
- step
- Read readings.csv
- kind
- report run
- when
- import
| step | kind | when |
|---|---|---|
| Read readings.csv | report run | import |
Follow the operations
1. Steps currently performed by the report module
- step
- Define summarize_alerts
- kind
- definition
- when
- import
- step
- Read readings.csv
- kind
- report run
- when
- import
- step
- Print the report
- kind
- report run
- when
- main
step kind when Define summarize_alerts definition import Read readings.csv report run import Print the report report run main 2. Read a field from every record
- 0definition
- 1report run
- 2report run
3. Match a text value
- 0false
- 1true
- 2true
4. Read a field from every record
- 0import
- 1import
- 2main
5. Match a text value
- 0true
- 1true
- 2false
6. Require both decisions
- 0false
- 1true
- 2false
7. Keep flagged entries
- step
- Read readings.csv
- kind
- report run
- when
- import
step kind when Read readings.csv report run import 8. Result
- step
- Read readings.csv
- kind
- report run
- when
- import
step kind when Read readings.csv report run import
The rows describe a small Python module. These blocks inspect that description; the Python challenge separates reusable helpers from the application entry point.
1. A module owns a namespace
A Python file can be imported as a module. Its namespace contains named objects such as functions and constants. import statistics lets the caller use statistics.mean without copying its implementation. An explicit from import can also be clear when the imported name's origin is apparent.
Avoid wildcard imports in ordinary application code. They hide which module supplied a name and can overwrite another name.
Import an explicit calculation
The caller supplies values rather than allowing the function to choose a file.
import statistics
def summarize(values):
return {"count": len(values), "mean": statistics.mean(values)}
print(summarize([6, 10, 14])){'count': 3, 'mean': 10}The module name identifies the source of mean. The report calculation remains independent of input collection.
2. Separate importing from running
Python executes top-level statements when it first imports a module in a process. A function definition creates a callable; it does not run the function body. A top-level function call does run immediately.
Put application work in main and call it under the __name__ == "__main__" guard. This condition is true when the module is the entry point and false when another module imports it by its module name. Keep unnecessary work outside the guard out of module initialization too.
Make the application call explicit
The browser runs this program as the entry point.
def format_report(values):
return f"Readings: {len(values)}"
def main():
print(format_report([8, 12]))
if __name__ == "__main__":
main()Readings: 2A local caller could import format_report without running main. The import still performs normal module initialization.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What does the statistics prefix identify in this call?
Question data
import statistics
statistics.mean([6, 10, 14])3. Keep dependency direction understandable
A command-line module can import a calculation and pass its arguments. The calculation should not import the command-line module to discover a filename. That direction keeps the calculation usable from tests and other applications.
Circular imports can expose partially initialized modules. Moving imports inside functions may defer a symptom, but the responsibilities still deserve review. Genuinely shared behavior can live in a module both callers depend on.
4. Distinguish public interfaces from conventions
Choose a small set of names callers should rely on. An underscore prefix signals an internal convention, not an access-control mechanism. Documentation should state the promised inputs, outputs and exceptions of the public interface.
A package organizes modules beneath a shared name. Do not create a new file for every function merely to increase the number of modules; related behavior can remain together.
5. Choose a project layout for how it runs
A small application can begin with a few clearly named files. A src layout places the importable package under src and normally requires installing the project in its environment. This helps distinguish an installed package from an accidental working-directory import.
A flat layout can also be appropriate. Directory structure alone does not improve a design or establish which copy a test imported. The next lesson explains environments and project metadata. Keep tests separate from application entry-point work.
Check yourself
Questions on Parts 1 to 5
Question 1 of 4
What does the usual guard permit?
Question data
A file runs directly with __name__ equal to __main__.Try it with Botie
Build with Botie
Write and run Python