Lesson · Capstone Core-Python Skills
Build a Reusable Python Package
150 min readBuild a Reusable Python Package
This capstone turns reusable code into an installable package with a deliberate public API, type hints, tests, documentation, versioning, and modern `pyproject.toml` metadata.
Learning goals
- Lay out a
src/package so importable code, tests, docs, and build metadata stay separate, and say which direction imports may travel. - Curate
__init__.pyso it re-exports the small set of names that form the public API, and explain why everything else stays internal. - Add type hints to public functions and ship the
py.typedmarker so a consumer's type checker reads them. - Write a
pyproject.tomlwith build metadata and a version, and build a wheel and a source distribution from it. - Describe a versioning and deprecation policy: what each version bump promises and how a breaking change is announced.
Mental model
The package's center of gravity is the public surface: callers import names from textstats, not from textstats.core, and that one rule lets internals move freely. The build metadata then describes the package to tools (name, version, backend) while py.typed tells type checkers that the annotations inside are worth reading. Building the wheel and installing it into a clean environment is the test that all of these pieces agree.
Mental model
read it top to bottom
src/<package>/: implementation modules (internal, free to move) ↓ __init__.py re-exports the chosen names public API: the smallest surface callers import ↓ pyproject.toml: name, version, build system wheel and sdist, installable into a clean environment
Core idea
A reusable package is defined by its contract with strangers: a small public API, annotations that tools can read, and metadata that builds and installs without the author's machine. Everything else, the internal module layout, the test files, the docs, exists to support that contract, and each piece is verifiable: import from a clean environment, build the artifacts, run the documented examples.
Package structure
A reusable package should separate public modules from internal implementation, tests, documentation, and build metadata. Use structure to make dependency direction obvious.
Public API design
Expose the smallest stable set of names callers need. Internal helpers can then move or change without forcing every user to update.
Type hints
Type hints on public functions and classes state the shape of values going in and coming out, and they travel with the code as machine-readable documentation. For an installed package, the py.typed marker is what tells a consumer's type checker to read the annotations; without it the hints exist but tools may ignore them. Hints are not enforced at runtime, so they document the contract rather than guard it.
Tests
Tests are how the package enforces its contract: unit tests pin the behavior of the public functions, and a small number of integration tests verify that the package works as installed rather than only inside the repository. Testing from a fresh virtual environment is the check that the dependencies declared in pyproject.toml are actually sufficient. A green suite is also what makes refactoring the internal modules safe.
pyproject.toml
pyproject.toml stores build-system configuration and standardized project metadata. Many tools also place their configuration in tool-specific tables in the same file.
Documentation
Documentation for a package is the reader's path from knowing nothing to a first successful call: a README that installs it, one runnable example per public name, and notes on behavior callers cannot infer from signatures. It should live in the repository next to the code so it can change in the same commit, and its examples should run against the built artifact, not only the source tree. When an example stops matching behavior, treat it as a report that something is out of date.
Versioning basics
Version numbers communicate releases and compatibility expectations. A reusable package also needs a policy for deprecation and supported Python versions.
Walkthrough
src/textstats/separates the distributable package fromtests/,docs/, andpyproject.toml, and thesrc/layout forces the package to be imported as it would be installed rather than from the working directory.__init__.pyis where the public surface is curated: it re-exports the chosen names sofrom textstats import word_countworks whiletextstats.corestays an implementation detail free to change.py.typedis the marker that tells type checkers the installed package ships its annotations; without it, tools may treat the package as untyped even though the hints exist in the source.pyproject.tomlholds the build system, name, and version that turn the directory into wheel and source-distribution artifacts, so the internal layout matters less than what__init__.pyexports. Predict before building: which names belong in__init__.py, and what breaks if a caller importstextstats.coredirectly.
Experiments to try
- Build the smallest package as
src/textstats/with one public function re-exported, then import it from a sibling directory and record the import line that works. - Add a name to
__init__.py, then remove it and record theImportErrora caller sees; decide whether the name deserves a place on the public surface. - Add hints to a public function, create the
py.typedmarker, and run a type checker against a caller that passes the wrong type; compare the report with the one from before the marker existed. - Write a minimal
pyproject.toml, build a wheel with the standard build tool, install it into a fresh virtual environment, and record the one-line import that proves it installed.
Capstone specification
Turn a useful component from an earlier project into a reusable package.
Common mistakes
- Treating the directory tree as the public API: if callers import
textstats.core, moving or splittingcore.pybreaks them even though__init__.pynever promised that path; the public surface is what__init__.pyexports, and deep imports should be treated as internal. - Shipping hints without
py.typed: the annotations exist in the source, but an installed consumer's type checker may ignore them and report missing types for a package that looks fully annotated. - Editing after building: a wheel is a snapshot, so a fix made after the build is missing from the installed artifact; rebuild before testing the install, and do not debug the source tree when the artifact is the thing users have.
- Versioning on vibes: a minor bump that removes a parameter breaks callers who trusted the compatibility promise, so the policy (patch for fixes, minor for additions, major for removals) must match what actually changed.
Practice: Easy
- Create the
src/textstats/layout with one public function re-exported from__init__.py; import it from outside the package directory and record the line that works. - Remove a name from
__init__.pyand record theImportErrorits caller now gets; restore it and decide whether it belongs on the public surface. - Add hints to a public function, add the
py.typedmarker, and check how a type checker reports a caller that passes the wrong type.
Practice: Medium
- Move a function from
core.pyinto a new internal module, update the re-export in__init__.py, and prove that a caller using the public name is unaffected. - Write the
[project]table of apyproject.toml(name, version, description,requires-python), build a wheel, and record which files land inside the artifact. - Write the README's first section with an installation line and one runnable example per public function; run every example in a clean environment and fix anything that does not hold.
Practice: Hard
- Turn a component from an earlier project into the specified package: curated public API, hints with
py.typed, tests, README examples,pyproject.toml, wheel and sdist builds; install the wheel into a fresh virtual environment and run the examples there. - Write the versioning and deprecation policy: what each part of
major.minor.patchpromises, how a deprecation is announced and for how long, and howrequires-pythonrelates to the policy; test the policy against two changes (adding an optional parameter, removing one). - Audit the public surface: list every name exported by
__init__.py, mark which are promised long term, move the rest behind internal modules, and prove that internal moves do not break a caller that sticks to the public names.
Lesson checklist
- I can lay out a
src/package and say what belongs in the importable tree, the tests, and the metadata. - I can curate
__init__.pyso the public API is a deliberate list rather than an accident of file layout. - I can add
py.typedand explain what changes for a consumer's type checker. - I can build a wheel, install it into a clean environment, and run the documented examples there.
Remember
A reusable package is a contract with people you will never meet: a small public API curated in `__init__.py`, annotations that tools read because `py.typed` says so, and `pyproject.toml` metadata that produces an artifact installable in a clean environment. The internals exist to serve that contract, and the evaluation questions (can modules move, does it install, do the artifacts contain what users need) all ask whether the contract actually holds.
Interview angles
What is the main purpose of **Package structure**?+
A reusable package should separate public modules from internal implementation, tests, documentation, and build metadata. Use structure to make dependency direction obvious.
What should you pay attention to when using **Public API design**?+
Expose the smallest stable set of names callers need. Internal helpers can then move or change without forcing every user to update.
How does **Type hints** fit into this lesson?+
Hints on public functions state value shapes for readers and tools, and the py.typed marker is what tells an installed consumer's type checker to trust them. Hints remain documentation at runtime: they are not enforced, so they constrain nothing until a checker or a tested boundary does.
Why is importing `textstats.core` in user code a problem even though it works?+
It works because modules are importable, but it treats an internal module as public: the package's promise lives in textstats/__init__.py, so core.py stays free to move or split only while callers do not depend on its path. Deep imports turn routine refactoring into a breaking change.