Project Structure and Packaging
Organize Python code into modules and packages, document projects, write tests, manage dependencies, and understand modern packaging configuration.
In this lesson, you will learn
- ✓Distinguish Python modules, packages, and projects.
- ✓Explain how imports connect code across files.
- ✓Recognize the roles of README.md, tests, requirements.txt, and pyproject.toml.
- ✓Build and trace a small, organized Python project.
- ✓Explain the difference between running a project from its directory and installing it as a package.
- ✓Apply basic project organization and dependency-management practices.
1. What is a Python project?
A Python project is a collection of files that work together to provide an application, library, command-line tool, or another useful piece of software.
A tiny script might need only one .py file. A larger application usually benefits from separating code, tests, documentation, and configuration.
Project structure is not just about creating folders. Each file should have a clear responsibility so developers can find code, test behavior, install dependencies, and understand how to run the project.
A simple project layout
README.md explains the project and how to use it. requirements.txt can list runtime dependencies when that workflow is appropriate. pyproject.toml stores project metadata and build-tool configuration. src/calculator/ contains the application's importable Python package. operations.py contains calculation functions. __init__.py marks the calculator directory as a regular Python package in this example. tests/test_operations.py contains automated tests.
Note
2. Modules: one Python file with reusable code
A Python module is a file containing Python code, usually with a .py extension. Functions, classes, and constants defined in a module can be imported by other code.
For example, operations.py can contain arithmetic functions while another file imports and uses them. This keeps the calculation logic separate from the code that asks for input or displays results.
When Python executes an import, it searches for a matching module or package using its import system. The current working directory and configured import paths can affect which modules are found.
Create operations.py
The file defines two functions. Defining these functions does not print anything. Other Python code can import them and call them.
Note
4. Build the calculator project
Now put the ideas together using a src layout. The src directory contains the importable package, while tests contains automated tests. This separation helps catch mistakes where code imports successfully only because the project root happens to be on the import path.
Create the following files. Keep each code example in its own file rather than pasting all the examples into one script.
src/calculator/operations.py
The module contains four focused arithmetic functions. divide checks for a zero divisor and raises ValueError rather than silently producing an invalid result. Raising an exception makes the failure explicit so the calling code can handle it.
Note
5. README.md: explain the project to people
README.md is usually the first documentation file someone sees when opening a repository. It explains what the project does, how to set it up, and how to run or test it.
Markdown is a plain-text format that supports headings, lists, links, code blocks, and other readable formatting.
A useful README should tell a new developer what they need, which setup commands to run, how to use the project, and how to run its tests. Avoid documenting commands that do not match the actual project.
Example README.md
The heading identifies the project. The requirements section states a Python version expectation; choose a version that matches the project's actual support policy. The installation command assumes pyproject.toml contains valid build-system and project configuration. The example demonstrates the public import path. The test command runs unittest discovery in the tests directory.
6. Tests: check that behavior stays correct
Tests are code that checks whether other code behaves as expected. They help detect mistakes and protect against accidental regressions when the project changes.
Python includes unittest in its standard library. A test class normally inherits from unittest.TestCase, and test methods usually begin with test_. Assertions compare actual results with expected results.
Tests should cover normal behavior and important failure cases. For the calculator, testing division by zero matters because the function deliberately raises ValueError.
tests/test_operations.py
Each test method checks one behavior. assertEqual compares the actual result with the expected value. assertRaises verifies that the operation raises the expected exception. The main guard allows the test file to be run directly, while unittest discovery can also find the tests.
Note
7. requirements.txt: record dependencies
A dependency is software your project relies on. For example, an application may depend on an external HTTP client or data-processing library.
requirements.txt is commonly used to record packages that pip should install. It can list pinned versions, version ranges, or other supported requirement specifiers.
The calculator example uses only the Python standard library, so it does not need third-party runtime dependencies. An empty or unnecessary requirements.txt should not be added just for appearance.
For an application, a requirements file is often a convenient way to reproduce an environment. For a reusable installable package, declare its runtime dependencies in project metadata so installation tools can resolve them automatically.
Example requirements.txt for an application using requests
This line declares a version range for the third-party requests package. It does not pin one exact release. A version range can allow compatible updates, but reproducibility may require a separate lock or fully pinned environment file. This is an illustrative example, not a dependency needed by the calculator project.
8. pyproject.toml: project metadata and build configuration
pyproject.toml is a TOML configuration file used by Python packaging tools. It can describe the project, declare dependencies, and configure the build backend and development tools.
The [build-system] table specifies which build backend to use and the build requirements. The [project] table contains metadata such as the distribution name, version, supported Python versions, and runtime dependencies.
The following example uses setuptools as the build backend and explicitly configures the src layout. This is important: a src directory does not automatically become an importable package just because the folder exists.
The distribution name used for installation does not have to be identical to the Python import package name, although this example uses calculator for both.
pyproject.toml for the calculator project
build-system tells packaging tools how to build the project. name and version identify this distribution. readme points to the project's README file. requires-python declares the Python versions the project supports. package-dir maps the package root to src. packages.find tells setuptools to discover packages under src.
Caution
9. Run and test the project
A predictable setup process helps teammates reproduce your environment. Create a virtual environment, install the project, and then run its tests from the project root.
The commands below assume the files shown in this lesson are in place and the active Python installation is compatible with the project's requires-python declaration.
Development workflow
The first command creates a virtual environment in .venv. The second installs the project in editable mode and uses the build configuration. The third discovers and runs the tests in tests. Test output depends on the test runner and results; it is intentionally not represented as a guaranteed fixed transcript.
10. Common layout mistakes and good habits
Keep source code, tests, documentation, and configuration easy to distinguish. A clear structure reduces confusion as the project grows.
Avoid naming your own files after standard-library modules or popular dependencies. For example, a local json.py can interfere with imports that expect Python's json module.
Avoid putting every implementation detail into __init__.py. It is often best to keep implementation in focused modules and expose only the intended public interface.
Do not commit a virtual environment directory such as .venv to version control. Document setup instructions and commit the source and configuration files needed to recreate the environment.
Use relative imports within a package when they improve clarity, and prefer documented package imports for code that is intended to be used from outside the package.
A file layout is a design decision, not a substitute for testing. A well-organized project can still contain bugs, and tests cannot compensate for unclear responsibilities by themselves.
A useful .gitignore
These patterns keep a local virtual environment and common Python bytecode artifacts out of version control. A .gitignore file does not remove files that are already tracked; those require a separate Git action if they should stop being tracked. Add other project-specific exclusions only when appropriate.
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Confusing a module with a package.
Why it happens: A module is typically one Python file, while a package groups related modules in a directory structure.
Key takeaway: A module is usually one Python file; a package groups related modules under a common namespace.
#2 Assuming Python automatically discovers every folder as an importable package in every project layout.
Why it happens: Import behavior depends on the project's layout, Python's search path, and packaging configuration; not every folder is automatically importable in every context.
Key takeaway: Check the import path and packaging configuration. For this src layout, configure package discovery and install the project.
#3 Putting all dependencies in documentation without declaring them for installation.
Why it happens: Documenting a dependency does not make it installable or reproducible; declare dependencies in the appropriate project metadata or requirements file.
Key takeaway: Declare third-party runtime dependencies in project metadata for a reusable package, or use a requirements file for an appropriate application workflow.
#4 Treating README.md as a substitute for configuration.
Why it happens: README.md explains a project's purpose and usage, while configuration files declare build settings, dependencies, and package metadata.
Key takeaway: Use the README to explain setup and usage, and use pyproject.toml and other configuration files to declare machine-readable project settings.
#5 Writing tests but never running them.
Why it happens: A test suite only provides feedback when it is executed; run tests locally and in automation to catch regressions.
Key takeaway: Run the test suite after meaningful changes and verify both successful cases and expected failures.
#6 Naming a project file after a standard-library module, such as json.py.
Why it happens: A local file named after a standard-library module can shadow the real module on the import path and cause confusing import failures.
Key takeaway: Choose distinctive filenames so local modules do not accidentally shadow modules Python or dependencies need to import.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is the difference between a module and a package?
Q2:Why do many Python projects use a src layout?
Q3:What is the role of README.md?
Q4:What is pyproject.toml?
Q5:What is the difference between requirements.txt and project dependencies?
Q6:What is an editable installation?
Q7:Why should a project include tests?
Q8:Why should __init__.py usually stay small?
Q9:Why should you avoid naming a file after a standard-library module?
Q10:How would you set up a new Python project for development?
Key takeaways
- A module is usually a Python file; a package organizes related modules under a namespace.
- Keep application logic, tests, documentation, and configuration in clearly defined places.
- README.md explains how people use the project.
- pyproject.toml stores project metadata and build configuration and can declare runtime dependencies.
- requirements.txt is useful for application dependency-installation workflows, while reusable distributions should declare runtime requirements in project metadata.
- Use tests to verify both expected results and important failure cases.
- A src layout works best when package discovery and installation are configured deliberately.
- A clear structure improves maintainability but does not replace testing.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: