Packaging
Learn how to turn your Python code into a real, installable package that anyone can use with pip install.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
📦 What You'll Learn
This lesson teaches you how to publish professional Python packages:
- Structuring a library properly
- Creating pyproject.toml configuration
- Building wheels and source distributions
- Uploading to TestPyPI and PyPI with twine
- Versioning and metadata best practices
- Making your package discoverable and trustworthy
After this lesson, anyone can install your code with:
📥 Python Download & Setup
Part 1: Package Structure & Building
1. What Is a Python Package?
Think of a package like a product in a box . The box (folder) contains everything needed: the product itself (your code), instructions (README), warranty info (LICENSE), and a label with specs (pyproject.toml). Anyone can "buy" your product with pip install !
A package is just a directory with an __init__.py file that can be imported.
File/Folder
Purpose
Required?
src/my_cool_lib/
Your actual library code
✅ Yes
pyproject.toml
Build config & metadata
README.md
Documentation (shown on PyPI)
✅ Highly recommended
LICENSE
Usage permissions
tests/
Unit tests
Optional but best practice
The src/ layout is recommended because it catches import mistakes early.
2. Basic Code Layout
3. The Modern Way: pyproject.toml
pyproject.toml is now the standard way to describe:
- Project metadata (name, version, description)
- Build backend (like setuptools)
- Dependencies
Key points:
- name → must be unique on PyPI
- version → follows semantic versioning (e.g. 0.1.0)
- requires-python → minimum Python version you support
- dependencies → packages installed when someone installs your library
4. Semantic Versioning (How to Version Properly)
Think of versions like software updates on your phone . A PATCH (15.0.1 → 15.0.2) fixes bugs quietly. A MINOR update (15.1) adds features. A MAJOR update (15 → 16) might change everything and require you to relearn things — that's a breaking change.
Part
When to Bump
Example
PATCH
Bug fixes, no breaking changes
0.1.0 → 0.1.1
MINOR
New features, backwards compatible
0.1.1 → 0.2.0
MAJOR
Breaking changes
0.2.0 → 1.0.0
Store the version in one place (e.g. __init__.py) and keep pyproject.toml in sync or use a tool like setuptools-scm later.
5. Writing a Good README for PyPI
Your README.md becomes the landing page on PyPI.
- Short description
- Installation instructions
- Basic usage example
- Features list
- Links (docs, repo, issues)
Make sure readme = "README.md" is set correctly in pyproject.toml.
6. Building the Distribution (Wheel + sdist)
Building a package is like baking bread. sdist is like shipping the recipe and ingredients — the customer bakes it themselves. Wheel is like shipping the finished loaf — ready to eat immediately. Most people prefer the wheel (faster to install)!
Then from your project root (same folder as pyproject.toml):
Type
File Extension
Install Speed
When Used
Wheel
.whl
⚡ Fast
Default installation
sdist
.tar.gz
🐢 Slower
Fallback, building from source
7. Uploading to TestPyPI (Safe Practice Run)
Before using the real PyPI, publish to TestPyPI.
- username: often __token__ if using API tokens
- password: your TestPyPI API token
If everything looks good, you're ready for real PyPI.
8. Publishing to the Real PyPI
- Create an account on pypi.org
- Generate an API token
- Configure ~/.pypirc (optional but helpful):
9. Updating Your Package (New Versions)
- Bump the version (e.g. 0.1.0 → 0.1.1) in: pyproject.toml
- __init__.py (if you mirror the version there)
- Rebuild: python -m build
- Upload again: twine upload dist/*
PyPI will reject duplicate versions, so you must use a new version number each time.
10. Minimal Checklist Before Publishing
- Package name is unique on PyPI
- Code is inside src/your_package_name/
- __init__.py defines __version__
- pyproject.toml is valid and has metadata
- README.md exists and readme is set in pyproject.toml
- Build succeeds (python -m build)
- TestPyPI upload + install works
- Version is bumped for each release
Part 2: Advanced Package Features
11. Adding Optional Features With "Extras"
Sometimes you want optional dependencies that users can install only if they need them.
Example: a core library with an optional cli or dev feature:
This keeps the base install lightweight, while still offering powerful extras for people who want them.
12. Entry Points & Console Scripts (Installing a CLI)
You can ship a command-line tool with your package so users get a global command after installing.
This is how black, pytest, pip, etc. expose commands.
13. Classifiers: Telling PyPI & Tools What Your Package Supports
- Supported Python versions
- Intended audience
- Topic (e.g. web, ML, data)
- Discoverability on PyPI
- Confidence for users (they can see support clearly)
- Filtering in tools / searches
14. Handling Dependencies Safely
1. Pin or semi-pin versions in development, but keep install requirements slightly relaxed.
In your own dev environment you can use a lock file from tools like pip-tools, Poetry, or uv.
2. Avoid unnecessary dependencies
- Easier to install
- Less likely to break
3. Put dev-only tools into optional dev extras, not into main dependencies.
15. Testing Before Publishing
Before uploading to PyPI, always run tests in a clean environment.
- -e → editable install (imports code directly from src/)
- .[dev] → includes dev dependencies from optional-dependencies
If tests pass in a clean venv, chances are much higher that users won't hit import errors.
16. Testing Installation Like a Real User
After building and uploading to TestPyPI, test your package the way a real user would:
- Create a fresh venv:
- Install from TestPyPI:
- Open Python and try:
If that works, your packaging, imports, and metadata are all aligned correctly.
17. Common Packaging Mistakes (and How to Avoid Them)
a) Forgetting __init__.py
If __init__.py is missing, Python won't treat the directory as a package.
b) Wrong where for packages
If you use the src/ layout, you must tell setuptools:
Otherwise your built wheel may contain no code, and imports will fail.
c) Importing the package from the project root during dev
- Use pip install -e . and run scripts via python -m my_cool_lib.something , or
- Put your scripts under src/ and run through modules
d) Uploading the same version twice
PyPI will reject re-uploads of a version. If you made a mistake:
- Bump the version (e.g. 0.1.0 → 0.1.1)
- Rebuild with python -m build
- Upload again with twine
18. Keeping Secrets Safe (Do Not Hardcode Keys)
Never put secrets (tokens, passwords) in your package.
- Use environment variables ( os.environ["MY_API_KEY"] )
- Or read from config files that are not in the published package
- Or let users pass keys into your functions/classes
Anything inside src/ will be visible to anyone on PyPI or GitHub, so treat it as public.
19. Automating Publishing With CI (Overview)
Later on, you can automate releases using CI like GitHub Actions.
- Tag a release (e.g. v0.2.0)
- CI workflow runs: installs dependencies
- builds package ( python -m build )
- uploads with twine using a PyPI token stored as a secret
Very rough example .github/workflows/release.yml structure:
After this, releasing is as simple as pushing a tag.
20. Making Your Package Friendly for Contributors
A polished package is easier for others to use and contribute to.
- Include a CONTRIBUTING.md explaining: how to set up dev environment
- how to run tests
- coding style or lint rules
- Add a simple Makefile or tasks.py with shortcuts
- Use a linter/formatter (ruff, black, isort) and mention them in dev extras
21. Summary of the Packaging Workflow
- Create Structure Use src/your_package/ layout. Add __init__.py, modules, tests
- Describe Project Create pyproject.toml with metadata, dependencies, optional extras, scripts
- Write Code + Tests Implement core logic. Add unit tests with pytest
- Build python -m build
- Test on TestPyPI Upload with twine to TestPyPI. Install in a clean venv. Import and run sample code
- Publish to PyPI Configure PyPI token. twine upload dist/*
- Repeat with New Versions Bump version for each change. Rebuild and re-upload
Part 3: Professional Polish & Best Practices
22. Handling Versioning Properly (Semantic Versioning Made Simple)
PyPI expects clear, predictable versioning. The best standard is SemVer:
- MAJOR → breaking changes
- MINOR → new features, no breaks
- PATCH → bug fixes
- 1.0.0 → first stable release
- 1.1.0 → added new features
- 1.1.5 → bug fixes only
23. Cross-Platform Compatibility
Make your package work on Windows, macOS, and Linux.
24. Adding Type Hints for Better DX (Developer Experience)
Typed packages are dramatically easier to use.
- Inline type hints
- Or a separate py.typed file to mark package typing support
This lets editors like VSCode, PyCharm & MyPy give:
- Autocomplete
- Type checking
- Safer refactors
Typed libraries are considered higher-quality on PyPI.
25. Adding Documentation (README, Examples, Tutorials)
- A clear README
- Usage examples
- API documentation
- Badges (version, downloads)
- Feature list
- Contribution guide
PyPI will display this directly on the project page.
26. Adding a License (Important for Public Use)
If you publish to PyPI without a license, companies legally cannot use your code.
- MIT License (very permissive)
- Apache 2.0 (enterprise-friendly)
- GPL (viral, requires open sourcing forks)
Add a LICENSE file at project root and reference it in pyproject.toml:
27. Keeping Your Package Secure
PyPI packages must remain safe. Follow these guidelines:
- OAuth tokens
- Database passwords
- Embedded credentials
- Using eval()
- Arbitrary imports based on user input
- Downloading code from the internet
Security matters for your reputation and your package's adoption.
28. Distributing Both sdist and Wheel (Why It Matters)
When you run python -m build , you get two types of packages:
- mycoollib-1.0.0.tar.gz → source distribution
- mycoollib-1.0.0-py3-none-any.whl → wheel
- sdist = source code (for platforms that build from scratch)
- wheel = pre-built, faster installs
Wheels install instantly and are preferred on modern Python.
29. Supporting Multiple Python Versions
You choose which Python versions your package supports.
to test on multiple interpreters. This makes your package more stable and predictable for users.
30. Writing a Professional __init__.py
Your package's public API should be explicitly controlled.
- Clear public interface
- Cleaner imports for users
- No accidental API exposure
Good packages have well-designed import paths.
31. Packaging Non-Python Files (Assets, Templates, etc.)
- Config templates
- JSON/YAML files
- Static resources
- HTML templates
This is cleaner than bundling file paths manually.
32. Popular Tools That Improve the Publishing Workflow
- black — automatic formatting
- ruff — ultra-fast linting
- mypy — typing enforcement
- pre-commit — hooks to auto-format before commit
- uv/Pipenv/Poetry — dependency managers
33. Final Practical Checklist Before Publishing
Here is the final checklist used by professional Python maintainers:
- ✓ Project structure correct
- ✓ pyproject.toml complete
- ✓ Version bumped
- ✓ Tests pass
- ✓ README is clear
- ✓ LICENSE added
- ✓ No secrets
- ✓ Build successful
- ✓ TestPyPI upload & install verified
- ✓ Publish to PyPI
🎓 Final Summary
You've now mastered professional Python package publishing to PyPI.
- Structure a library with src/ layout
- Configure pyproject.toml with all metadata
- Build wheels and source distributions
- Test on TestPyPI before publishing
- Publish to PyPI with twine
- Version properly with semantic versioning
- Add optional extras and CLI tools
- Keep packages secure and cross-platform
- Automate releases with CI/CD
These skills let you publish professional Python libraries used by developers worldwide — just like requests, FastAPI, and thousands of other packages on PyPI.
📋 Quick Reference — Packaging & PyPI
Tool / File
What it does
Modern project metadata and build config
python -m build
Build wheel and sdist
twine upload dist/*
Upload to PyPI
twine check dist/*
Validate package before upload
pip install -e .
Install package in editable/dev mode
You can now package your Python code and publish it to PyPI — making your work installable by anyone in the world with pip.
Up next: Files & Streams — work with large datasets, binary files, and efficient I/O patterns.
Practice quiz
Which file is the modern standard for declaring a package's metadata and build config?
- setup.cfg
- requirements.txt
- pyproject.toml
- MANIFEST.in
Answer: pyproject.toml. pyproject.toml is the modern standard describing metadata, build backend, and dependencies.
What command builds both a wheel and a source distribution (sdist)?
- python -m build
- pip install .
- twine upload dist/*
- python setup.py register
Answer: python -m build. python -m build produces the .whl (wheel) and .tar.gz (sdist) in the dist/ folder.
What is the difference between a wheel and an sdist?
- A wheel is source code; an sdist is pre-built
- They are identical formats
- A wheel can't be uploaded to PyPI
- A wheel is a pre-built package (faster install); an sdist ships source to build from
Answer: A wheel is a pre-built package (faster install); an sdist ships source to build from. Wheels (.whl) install fast as pre-built; sdists (.tar.gz) contain source built on the user's machine.
Which tool uploads your built distributions to PyPI?
- pip
- twine
- build
- setuptools
Answer: twine. twine upload dist/* publishes your wheel and sdist to (Test)PyPI.
In MAJOR.MINOR.PATCH semantic versioning, which part bumps for a breaking change?
- MAJOR
- PATCH
- MINOR
- None of them
Answer: MAJOR. Breaking changes bump MAJOR; MINOR adds backward-compatible features; PATCH is bug fixes.
Why is publishing to TestPyPI recommended before the real PyPI?
- It is required by law
- TestPyPI packages auto-publish to PyPI
- It's a safe practice run to verify upload and install without affecting the real index
- It makes the package free
Answer: It's a safe practice run to verify upload and install without affecting the real index. TestPyPI lets you rehearse uploading and installing safely before the real release.
What happens if you try to upload a version that already exists on PyPI?
- It silently overwrites the old one
- PyPI rejects the duplicate; you must bump to a new version number
- It merges the two uploads
- It deletes the package
Answer: PyPI rejects the duplicate; you must bump to a new version number. PyPI forbids re-uploading the same version, so each release needs a new version number.
With the src/ layout, what tells setuptools where to find your package?
You must point package discovery at src via [tool.setuptools.packages.find] where = ["src"].
How do users install an optional 'extras' group, e.g. a cli extra?
- pip install my-cool-lib --cli
Extras declared under [project.optional-dependencies] are installed with the bracket syntax pkg[extra].
Which pyproject.toml section ships a console command like 'mycool'?
[project.scripts] maps a command name to a function entry point (e.g. my_cool_lib.cli:main).
Continue this course
- Next: Files & Streams