π€ Packaging & Publishing to PyPI
in Python
Learn Python packaging step by step: pyproject.toml, src layout, wheels and sdists, semantic versioning, TestPyPI and safe publishing to PyPI.
What this lesson is about
Packaging is the skill that turns a folder of scripts into something other people can install with a single pip install command. Every library you have ever used, from requests to numpy, went through the same steps: a project layout, a metadata file, a build, and an upload to an index. Once you understand those steps, you can share your own tools with teammates, with friends, or with the whole world.
In real work, packaging shows up far more often than people expect. A company with three services that share some helper code will put that code in an internal package. A data scientist who keeps copying the same cleaning functions between notebooks will get tired and package them. Even if you never publish publicly, pip install -e . on your own project is the cleanest fix for the dreaded import errors that appear when scripts live in different folders.
This lesson is organised the way I would build a package from nothing. First the mental model (source tree, sdist, wheel), then the src layout, then pyproject.toml, then versioning, building, testing on TestPyPI, and finally publishing safely. Many of these steps need command line tools that cannot run inside a web page, so those code blocks are marked as static. Alongside them I have written small runnable simulations, such as parsing a real pyproject.toml string with tomllib, comparing versions, and peeking inside a wheel, so you can experiment right here.
What you will learn
- βThe difference between a source tree, an sdist and a wheel
- βWhy the
srclayout prevents a whole class of import bugs - βHow to read and write a
pyproject.tomlfollowing PEP 621 - βHow build backends and
python -m buildfit together - βHow semantic versioning works and how to compare versions in code
- βHow entry points create command line tools when your package is installed
- βHow to test an upload on TestPyPI before the real index
- βHow trusted publishing and API tokens keep your credentials safe
Why programmers should learn this
- β Packaging ends the copy-and-paste habit: one installable library replaces five slightly different copies of the same helper file.
- β
pip install -e .gives your project a stable import path, so tests, notebooks and scripts all import it the same way. - β A published package with a clear README, licence and version history is one of the most credible things you can show on a portfolio or in a job application.
- β Understanding wheels, sdists and build backends makes installation errors readable instead of mysterious, which saves hours when a build fails on someone else's machine.
- β
Teams ship internal tools as packages with entry points, so a command like
mytool runworks the same on every laptop and in every CI job.
What a Python package really is
People use the word package loosely. Strictly, an import package is a folder containing an __init__.py file that you import in code. A distribution package is the thing you install with pip: a single archive file with metadata attached. One distribution usually contains one import package, but the names do not have to match. You pip install scikit-learn and then import sklearn, which trips up almost every beginner at least once.
There are two kinds of distribution files. A source distribution (sdist) is a .tar.gz of your source plus metadata; installing it means running the build step on the user's machine. A wheel is a .whl file, which is just a zip archive that is already built, so pip can unpack it straight into site-packages. Wheels install quickly and predictably, so you should always publish one wheel, and publish the sdist too so people on unusual platforms can still build from source.
The wheel filename is not decoration. It encodes the project name, the version, the Python tag, the ABI tag and the platform tag, separated by dashes. A pure Python project produces something like mylib-1.0.0-py3-none-any.whl, which means any Python 3 on any platform. Libraries with compiled extensions produce one wheel per platform. Let me show you how to read those names with code, which makes the idea concrete.
def parse_wheel_name(filename):
stem = filename.removesuffix(".whl")
parts = stem.split("-")
# name-version[-build]-python-abi-platform
if len(parts) == 6:
name, version, build, py, abi, plat = parts
else:
name, version, py, abi, plat = parts
build = None
return {"name": name, "version": version, "python": py,
"abi": abi, "platform": plat, "build": build}
for fn in ["mylib-1.0.0-py3-none-any.whl",
"numpy-2.1.0-cp312-cp312-manylinux_2_17_x86_64.whl"]:
info = parse_wheel_name(fn)
pure = info["platform"] == "any" and info["abi"] == "none"
print(fn)
print(" ", info["name"], info["version"], "| pure python:", pure)mylib-1.0.0-py3-none-any.whl mylib 1.0.0 | pure python: True numpy-2.1.0-cp312-cp312-manylinux_2_17_x86_64.whl numpy 2.1.0 | pure python: False
Line by line
- 1-3Strip the
.whlending and split the stem on dashes into its tag fields. - 4-9A wheel name has five fields, or six when a build tag is present; unpack each case into named variables.
- 10-11Return the fields as a dictionary so the caller can use them by name.
- 13-15Two sample names: a pure Python wheel and a compiled one for CPython 3.12 on Linux.
- 16-19A wheel is pure Python when the ABI is
noneand the platform isany; print each name with that verdict.
The real packaging libraries do this parsing with more care for edge cases such as dashes inside names. This toy version is enough to build intuition.
The src layout and import safety
There are two common ways to arrange files. The flat layout puts the import package at the top level next to pyproject.toml. The src layout puts it one level down inside a folder called src. I recommend the src layout for anything you plan to distribute, and the reason is subtle but important.
With a flat layout, running python or pytest from the project root puts the root on the import path, so import mylib finds your working copy even if you never installed it. Your tests pass. Then you publish, and discover that the wheel forgot a data file or a subpackage, because the tests never exercised the installed copy. With the src layout, the code is not importable until you install it (usually with pip install -e .), so your tests always exercise the same thing your users will get.
The rest of a healthy project is simple: a tests folder beside src, a README.md, a LICENSE file, and pyproject.toml. Notice there is no setup.py in the list. Modern projects describe themselves declaratively in pyproject.toml, and a setup.py is only needed for rare, advanced build steps. Below, I print a project tree from a dictionary, which doubles as a handy way to plan a layout before creating any files.
layout = {
"mylib": {
"pyproject.toml": None,
"README.md": None,
"LICENSE": None,
"src": {
"mylib": {
"__init__.py": None,
"core.py": None,
"cli.py": None,
}
},
"tests": {
"test_core.py": None,
},
}
}
def print_tree(node, prefix=""):
names = sorted(node, key=lambda n: (node[n] is None, n))
for i, name in enumerate(names):
last = i == len(names) - 1
print(prefix + ("βββ " if last else "βββ ") + name)
child = node[name]
if child is not None:
print_tree(child, prefix + (" " if last else "β "))
print_tree(layout)βββ mylib
βββ src
β βββ mylib
β βββ __init__.py
β βββ cli.py
β βββ core.py
βββ tests
β βββ test_core.py
βββ LICENSE
βββ README.md
βββ pyproject.tomlLine by line
- 1-17A nested dict stands for the folder tree: a dict value is a folder,
Noneis a file. - 19Define a recursive function that prints one folder level.
- 20Sort so that folders come first and names are alphabetical; sorting also keeps the output stable.
- 21-23For each entry, work out whether it is the last at this level and print the right branch symbol.
- 24-26If the entry is a folder, recurse with a longer prefix so child lines line up under it.
- 28Print the whole tree starting from the top-level dict.
To create that structure for real you would make the folders and empty files by hand, or let a project template tool do it. What matters is that you understand each piece before a tool generates it for you.
pyproject.toml: your project's identity card
pyproject.toml is a TOML file with up to three kinds of tables you care about. The [build-system] table says which tool builds your project. The [project] table holds the metadata, which PEP 621 standardised: name, version, description, readme, Python requirement, licence, authors, dependencies and so on. Tool-specific settings live under [tool.something], for example [tool.pytest.ini_options].
A few fields deserve a closer look. requires-python tells pip which interpreters your package supports, and pip will refuse to install on older ones. dependencies lists what your package needs at runtime, with sensible lower bounds such as requests>=2.31; avoid pinning exact versions in a library, because that makes it impossible to install alongside other packages. optional-dependencies define extras like mylib[dev] for test tools. classifiers and keywords help people find you, and urls adds links on the PyPI page.
Python 3.11 added tomllib to the standard library, so you can read TOML without installing anything. It is read-only, which is fine, since you write the file by hand. Parsing your own pyproject.toml is a great way to understand that it is just data: a nested dictionary. The first block is the static file as you would save it, and the second parses an equivalent string so you can explore the structure.
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "mylib"
version = "0.1.0"
description = "A tiny example library"
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
authors = [{ name = "Your Name", email = "you@example.com" }]
keywords = ["example", "demo"]
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
]
dependencies = ["requests>=2.31"]
[project.optional-dependencies]
dev = ["pytest>=8"]
[project.scripts]
mylib = "mylib.cli:main"
[project.urls]
Homepage = "https://example.com/mylib"Line by line
- 1-3Declare the build backend;
hatchlingis one of several valid choices. - 5-8Name, version and a one line description; the name is what people type after
pip install. - 9-11Point at the README, state the minimum Python version and give an SPDX licence expression (needs a reasonably recent backend).
- 12-18Authors, search keywords and trove classifiers help humans and tools understand the project.
- 19Runtime dependencies with a lower bound, not an exact pin.
- 21-22An optional extra:
pip install mylib[dev]also installs pytest. - 24-25A console script: installing creates a
mylibcommand that callsmain()inmylib/cli.py. - 27-28Links shown on the project page.
import tomllib
text = """
[project]
name = "mylib"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["requests>=2.31", "rich"]
[project.scripts]
mylib = "mylib.cli:main"
"""
data = tomllib.loads(text)
project = data["project"]
print("name:", project["name"])
print("version:", project["version"])
print("needs:", project["requires-python"])
for dep in project["dependencies"]:
print("depends on:", dep)
print("scripts:", project["project.scripts"] if "project.scripts" in project else data["project"]["scripts"])name: mylib
version: 0.1.0
needs: >=3.10
depends on: requests>=2.31
depends on: rich
scripts: {'mylib': 'mylib.cli:main'}Line by line
- 1
tomllibships with Python 3.11 and newer; it only reads TOML. - 3-13A small pyproject string held in a normal triple quoted string.
- 15
loadsparses text into nested dictionaries and lists. - 16-21Tables become dictionaries, so
data["project"]gives the metadata table and the usual key lookups work. - 22
[project.scripts]is nested insideproject, so it is reached bydata["project"]["scripts"]; the conditional is just a safe lookup.
Because [project.scripts] becomes data['project']['scripts'], dotted table names are simply nested dictionaries. That one fact makes every TOML file easier to read.
Versioning and semantic versions
Versions tell your users how risky an upgrade is. The widely used convention is semantic versioning: MAJOR.MINOR.PATCH. You raise PATCH for backwards compatible bug fixes, MINOR for new backwards compatible features, and MAJOR when you break something existing users rely on. Python's own packaging rules (PEP 440) are a little richer, allowing pre-releases like 1.2.0rc1 and 1.2.0a3, but the three number core is what you will use most.
Comparing versions as strings is a classic trap: "1.10.0" < "1.9.0" is True as text because the character 1 sorts before 9. You must compare the numbers. In production code, use the packaging library's Version class, which handles every PEP 440 form. For learning, a tiny parser teaches the same lesson and shows why tuples are perfect here, since Python compares tuples element by element.
Where should the version live? Keep one source of truth. The simplest approach is the version field in pyproject.toml and nothing else. If your code needs to show its version, read it from the installed metadata with importlib.metadata.version("mylib") rather than copying the number into a second file where it can drift. Some projects use dynamic = ["version"] and derive it from git tags; that is valid, but start simple.
def parse(v):
major, minor, patch = v.split(".")
return (int(major), int(minor), int(patch))
def bump(v, part):
major, minor, patch = parse(v)
if part == "major":
return f"{major + 1}.0.0"
if part == "minor":
return f"{major}.{minor + 1}.0"
if part == "patch":
return f"{major}.{minor}.{patch + 1}"
raise ValueError("part must be major, minor or patch")
print("as text :", "1.10.0" < "1.9.0")
print("as tuple:", parse("1.10.0") < parse("1.9.0"))
v = "1.4.2"
for part in ["patch", "minor", "major"]:
print(part, "->", bump(v, part))
versions = ["1.10.0", "1.2.0", "1.9.3", "0.9.9"]
print(sorted(versions, key=parse))as text : True as tuple: False patch -> 1.4.3 minor -> 1.5.0 major -> 2.0.0 ['0.9.9', '1.2.0', '1.9.3', '1.10.0']
Line by line
- 1-3Split a version on dots and turn each piece into an integer, returning a tuple.
- 5-13
bumpraises one number and resets the lower ones to zero, exactly as semantic versioning says. - 15-16Compare as text and as tuples; the text comparison gives the wrong answer for
1.10.0versus1.9.0. - 18-20Show what each kind of bump does to
1.4.2. - 22-23Sorting with
key=parseorders versions numerically.
This parser rejects pre-releases and anything that is not three numbers. Use the packaging library when you must handle real world versions.
Entry points and installed metadata
When pip installs a wheel it also unpacks a .dist-info folder next to your code. That folder holds a METADATA file (name, version, dependencies, the README text) and an entry_points.txt file. The importlib.metadata module in the standard library reads those files, which is how a program can ask "what version of mylib is installed?" or "which plugins have registered themselves?"
An entry point is a named pointer of the form module:function. The [project.scripts] table you saw earlier is a special group of entry points: at install time pip generates a small launcher executable for each one, and running it imports the module and calls the function. Other groups, which you name yourself, let packages advertise plugins that your application can discover and load without knowing them in advance. Pytest uses that exact mechanism for its plugins.
To understand resolution, you only need two operations: split the string at the colon, import the module, then fetch the attribute. Below I model a fake installed distribution with a dictionary and resolve its entry points using importlib.import_module, using standard library functions as targets so the demo runs anywhere. In a real project the target would be your own mylib.cli:main.
import importlib
fake_dist = {
"name": "mylib",
"version": "0.1.0",
"entry_points": {
"console_scripts": {
"sqrt-tool": "math:sqrt",
"dump": "json:dumps",
},
},
}
def load(spec):
module_name, _, attr = spec.partition(":")
module = importlib.import_module(module_name)
return getattr(module, attr)
group = fake_dist["entry_points"]["console_scripts"]
for command in sorted(group):
func = load(group[command])
print(command, "->", group[command], "->", func.__name__)
print(load(group["sqrt-tool"])(144))
print(load(group["dump"])({"ok": True}))dump -> json:dumps -> dumps
sqrt-tool -> math:sqrt -> sqrt
12.0
{"ok": true}Line by line
- 1
importliblets code import a module from a string name. - 3-11A dictionary pretends to be the metadata pip would store for an installed package.
- 13-16
partitionsplitsmodule:functionat the colon; import the module, then fetch the named attribute. - 18-21Loop over the registered commands in sorted order and resolve each one to a real function.
- 23-24Call the resolved functions to prove they work.
from importlib.metadata import version, metadata, entry_points
print(version("mylib")) # the installed version string
meta = metadata("mylib")
print(meta["Name"], meta["Requires-Python"])
for ep in entry_points(group="console_scripts"):
if ep.name == "mylib":
print(ep.value) # mylib.cli:main
func = ep.load() # imports and returns mainLine by line
- 1These functions are all in the standard library.
- 3
versionreads the installed distribution's version, so you never need to duplicate it in code. - 4-5
metadatagives dictionary-like access to fields from the METADATA file. - 7-10
entry_points(group=...)lists registered pointers;.load()performs the import for you.
Building and inspecting your distributions
Building is a single command once your pyproject.toml exists. Install the build tool, run it from the project root, and it creates an isolated environment, installs your declared build backend there, and produces both an sdist and a wheel inside a dist folder. The isolation matters: it proves your project builds from its declared requirements and not from whatever happens to be installed on your laptop.
Before uploading anything, check it. twine check dist/* validates that the long description renders on PyPI, and you can open the wheel, because it is only a zip, to confirm the right files are inside. If your wheel is missing a data file or includes your tests folder by accident, you find out now instead of after release. Also test the wheel in a fresh virtual environment: create one, pip install dist/*.whl, and run your command or import your package. That is the only test that truly proves the artifact works.
To make the structure of a wheel less magical, the next block builds a miniature wheel in memory with the standard library zipfile module and lists what is inside. A real wheel has exactly the same shape: your package files plus a .dist-info folder with METADATA, WHEEL and RECORD. The metadata is plain text in an email header style format, which you can read with eyes alone.
# in a fresh virtual environment, from the project root python -m pip install --upgrade build twine python -m build twine check dist/* ls dist # mylib-0.1.0.tar.gz (sdist) # mylib-0.1.0-py3-none-any.whl (wheel) # prove the wheel works in a clean environment python -m venv /tmp/testenv /tmp/testenv/bin/pip install dist/mylib-0.1.0-py3-none-any.whl /tmp/testenv/bin/mylib
Line by line
- 1-2Upgrade
buildandtwineinside your own virtual environment. - 3Build the sdist and wheel into
dist/. - 4Validate metadata and README rendering.
- 5-7List the results; you should see one
.tar.gzand one.whl. - 9-11Create a throwaway environment, install only the wheel, and run the command; on Windows the paths use
Scriptsinstead ofbin.
import io
import zipfile
metadata = "\n".join([
"Metadata-Version: 2.1",
"Name: mylib",
"Version: 0.1.0",
"Requires-Python: >=3.10",
"Requires-Dist: requests>=2.31",
])
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as whl:
whl.writestr("mylib/__init__.py", "__version__ = '0.1.0'\n")
whl.writestr("mylib/core.py", "def hello():\n return 'hi'\n")
whl.writestr("mylib-0.1.0.dist-info/METADATA", metadata)
whl.writestr("mylib-0.1.0.dist-info/WHEEL", "Wheel-Version: 1.0\nTag: py3-none-any\n")
with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as whl:
for info in whl.infolist():
print(f"{info.file_size:4d} {info.filename}")
text = whl.read("mylib-0.1.0.dist-info/METADATA").decode()
fields = dict(line.split(": ", 1) for line in text.splitlines())
print(fields["Name"], fields["Version"], fields["Requires-Dist"])22 mylib/__init__.py 29 mylib/core.py 102 mylib-0.1.0.dist-info/METADATA 37 mylib-0.1.0.dist-info/WHEEL mylib 0.1.0 requests>=2.31
Line by line
- 1-2
io.BytesIOacts like a file in memory andzipfilewrites zip archives, which is all a wheel is. - 4-10Metadata is simple
Key: valuelines. - 12-17Create the archive and add two code files and two metadata files, using the same names a real wheel uses.
- 19-22Re-open the bytes for reading, list every member with its size and read the METADATA member.
- 24-25Turn the header-style lines into a dictionary and print three fields.
A real wheel also contains a RECORD file listing every member with a hash. Build tools create it for you.
TestPyPI, tokens and trusted publishing
PyPI releases are permanent. You can yank a release so installers skip it, but you cannot reuse a filename or change its contents, and the project name is yours only once you have claimed it. So rehearse first on TestPyPI, a separate index with its own accounts that exists precisely for practice. Upload there, create a clean environment, install from it, and check that the project page looks right. Remember that TestPyPI does not host your dependencies, so installing with it needs an extra index option that falls back to the real PyPI for them.
Authentication has moved away from passwords. Uploads use API tokens, which you generate in your account settings and which can be limited to a single project after the first upload. Treat a token like a password: never commit it to git, never paste it into a lesson or screenshot, and revoke it at once if it leaks. With twine you pass the username __token__ and the token as the password, usually via environment variables or a keyring, so the secret does not sit in a file in your repository.
The better option for projects hosted on a code forge with CI is trusted publishing. Instead of storing a long-lived secret, you tell PyPI "workflows from this repository, in this workflow file, are allowed to publish this project". At release time the workflow proves its identity with a short-lived token, which PyPI exchanges for a temporary upload credential. Nothing to rotate, nothing to leak. Check the current PyPI documentation when you set this up, because the screens and workflow snippets get refreshed. The block below shows the typical shape of a release job, with no secrets anywhere in it.
# 1. rehearse on TestPyPI (username is literally __token__) export TWINE_USERNAME=__token__ export TWINE_PASSWORD="paste-your-testpypi-token-here" twine upload --repository testpypi dist/* # 2. install from TestPyPI in a clean environment python -m venv /tmp/trial /tmp/trial/bin/pip install \ --index-url https://test.pypi.org/simple/ \ --extra-index-url https://pypi.org/simple/ \ mylib # 3. when happy, bump the version and publish for real export TWINE_PASSWORD="paste-your-pypi-token-here" twine upload dist/*
Line by line
- 1-4Set the username to
__token__and supply a token through the environment; the value shown is a placeholder, never a real secret. - 6-10Install your project from TestPyPI into a clean environment; the extra index lets pip fetch dependencies from the real PyPI.
- 12-14After a good rehearsal, publish to the real index; remember each version number can be used only once.
name: Publish
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python -m pip install build
- run: python -m build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
publish:
needs: build
runs-on: ubuntu-latest
environment: pypi
permissions:
id-token: write
steps:
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- uses: pypa/gh-action-pypi-publish@release/v1Line by line
- 1-4Run the workflow when a release is published.
- 6-18The build job installs
build, creates the distributions and saves them as an artifact. - 20-24The publish job runs in a protected environment and is granted permission to request an identity token; that permission is what trusted publishing relies on.
- 25-30Download the built files and hand them to the official PyPI publish action; no password or token appears anywhere.
Version numbers on PyPI can never be reused. If a release is broken, publish a new patch version and yank the bad one.
README, licence and a release checklist
Your README is the front page of the project on PyPI, so write it for a stranger: one sentence on what the library does, an install command, a short working example, and a link to deeper docs. Reference it from pyproject.toml with readme = "README.md". A licence file is not optional if you want others to use your code legally; without one, the default is that nobody may reuse it. Choose a well known licence such as MIT, Apache 2.0 or GPL based on what you want to allow, and name it in the metadata.
Quality gates are worth automating. Before every release I want to know that the metadata is complete, the version has been bumped, tests pass against the installed wheel, and the distribution files are what I expect. Since pyproject.toml is data, you can write a few lines of Python that audit it. The following block does exactly that on a sample string, reporting what is missing, the same idea as a linter, but for packaging.
Finish with a repeatable routine. Update the changelog, bump the version, commit, tag the commit with the version, build from a clean checkout, upload to TestPyPI, install and smoke-test, then publish. After the first time, it takes minutes, and every step guards against one particular kind of embarrassment.
import tomllib
REQUIRED = ["name", "version", "description", "readme",
"requires-python", "license", "dependencies"]
sample = """
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "mylib"
version = "0.1.0"
description = "A tiny example library"
requires-python = ">=3.10"
dependencies = []
"""
def audit(text):
data = tomllib.loads(text)
problems = []
if "build-system" not in data:
problems.append("missing [build-system]")
project = data.get("project", {})
for key in REQUIRED:
if key not in project:
problems.append(f"missing project.{key}")
return problems
issues = audit(sample)
for item in issues:
print("-", item)
print("ready to release" if not issues else f"{len(issues)} issue(s) to fix")- missing project.readme - missing project.license 2 issue(s) to fix
Line by line
- 3-4The metadata keys this checklist insists on.
- 6-17A deliberately incomplete sample file, with no readme or licence.
- 19-27Parse the text, then collect a message for every missing table or key.
- 29-32Print each problem and a final verdict; an empty list means the check passed.
Here is the checklist in prose so you can paste it into your own notes: name is free on the index, README renders, licence present, version bumped, tests green on the installed wheel, twine check clean, TestPyPI rehearsal done, tag created, then publish.
Common mistakes
β Comparing versions as strings
"1.10.0" < "1.9.0" is True for text. Always compare parsed numbers, or use the packaging library's Version class.
β Reusing a version number
PyPI refuses a second upload of the same filename, even if you deleted the release. Bump the version for every upload and rehearse on TestPyPI first.
β Leaking an API token
Pasting a token into code, a README or a commit lets anyone publish as you. Use environment variables or trusted publishing, and revoke any token that has been exposed.
β Testing only the source folder
With a flat layout your tests can pass without the package ever being installed. Use the src layout and test against an installed or editable copy so missing files show up before release.
β Pinning exact dependency versions in a library
Writing requests==2.31.0 forces every user into that version and causes conflicts. Use lower bounds, and an upper bound only when you know of a real incompatibility.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What is a wheel?
.whl file is a zip containing already built code and metadata, so installation is just unpacking.Q2. Which table in pyproject.toml names the build backend?
[build-system] holds requires and build-backend, which tell build frontends how to build the project.Q3. Why is the src layout recommended?
src stops the project root from silently satisfying imports, which hides packaging bugs.Q4. You release 1.4.2 with a backwards compatible new feature. What is the next semantic version?
Q5. What does the entry mylib = "mylib.cli:main" under [project.scripts] create?
mylib.cli and calls main.Q6. What is the main benefit of trusted publishing?
Frequently asked questions
Do I still need setup.py?
+Usually not. A pyproject.toml with a [build-system] table and a [project] table is enough for most pure Python projects. setup.py remains only for unusual custom build steps in some older projects.
Which build backend should I choose?
+Several are fine: setuptools, hatchling, flit-core and others all follow the same standard interface. For a simple pure Python library, pick one, learn its options, and stay with it. Check current documentation if you need compiled extensions.
Can I delete a bad release from PyPI?
+You can delete or yank it, but the filename can never be used again. Yanking keeps the file but makes installers skip it unless the exact version is requested. Publish a fixed new version either way.
What is an editable install?
+pip install -e . links your working folder into the environment so edits take effect immediately without reinstalling. It is the normal way to develop a package locally.
Is the package name case sensitive?
+Names are compared in a normalised form where case, dashes, dots and underscores are treated alike, so My_Lib and my-lib refer to the same project. Check the index for existing names before you pick one.
Key takeaways
- βA distribution is what you install; an import package is what you import, and the names can differ.
- βPublish both an sdist and a wheel, built with
python -m build. - β
pyproject.tomlwith[build-system]and[project]is the modern, declarative way to describe a package. - βUse semantic versions, compare them as numbers, and keep one source of truth.
- βRehearse on TestPyPI and verify the wheel in a clean environment before the real upload.
- βPrefer trusted publishing; if you use tokens, keep them out of your repository.