Packaging & Publishing to PyPI
Published by Brayan K
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.
From a folder of code to something pip installs
pip doesn't install a folder of code as it is. It installs a built file, and the kind this lesson makes is a wheel, a .whl file. The lesson builds one from a small project, installs it, and shows what installing leaves behind, then how the files reach PyPI, the Python Package Index, which pip's help names as its default index. Virtual Environments & Dependency Management Best Practices covered installing other people's packages into a venv, and its version rules apply here too.
Two names matter. Modules and Packages showed that you install beautifulsoup4 but import bs4. The name you install is the project's, the one PyPI lists. The name you import is the package folder's. This lesson's project is called my-cool-lib, and its package folder my_cool_lib:
my-cool-lib/
├── LICENSE
├── README.md
├── pyproject.toml
├── src/
│ └── my_cool_lib/
│ ├── __init__.py
│ ├── cli.py
│ └── core.py
└── tests/
└── test_core.pyThe package itself is three short files:
# src/my_cool_lib/core.py
def say_hello(name: str) -> str:
if not name:
raise ValueError("name must not be empty")
return f"Hello, {name}!"
# src/my_cool_lib/__init__.py
from .core import say_hello
__all__ = ["say_hello"]
# src/my_cool_lib/cli.py
import sys
from .core import say_hello
def main() -> int:
name = sys.argv[1] if len(sys.argv) > 1 else "command line"
print(say_hello(name))
return 0The package sits in src, the src layout that Module & Package Architecture for Large Codebases described. Measured from the project folder, python -c "import my_cool_lib" stops with ModuleNotFoundError: No module named 'my_cool_lib', because Python looks in the current folder, not in src. Installing the project is what makes the import work, from any folder, and that's what this lesson does. main() is written to become a command, as Building Command-Line Tools with argparse & Typer wrote its programs: it returns the exit status.
pyproject.toml describes the project
Everything a build needs to know goes in pyproject.toml, in the project's top folder. This one was built for this lesson on Python 3.10 to 3.14:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "my-cool-lib"
version = "0.1.0"
description = "A tiny example library."
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
dependencies = ["packaging>=24"]
[project.scripts]
cool-hello = "my_cool_lib.cli:main"- [build-system] names the build backend, the package that turns the project into files, here hatchling. For setuptools, the two lines are requires = ["setuptools>=77"] and build-backend = "setuptools.build_meta"; the rest of the file stays the same.
- [project] holds what pip and PyPI read: the project's name and version, a one-line description, the README, whose text goes into the metadata as the long description, the Pythons it works on, its license, and the packages it needs, with the version specifiers from Virtual Environments.
- [project.scripts] turns a function into a command: installing the project makes a cool-hello command that runs main() from my_cool_lib.cli.
license = "MIT" is a license expression, and with a LICENSE file next to it both backends put that file into the wheel. Two older forms give trouble with setuptools 84: license = { text = "MIT" } makes it print a deprecation warning that says "By 2027-Feb-18, you need to update your project", and a License :: OSI Approved :: MIT License classifier next to license = "MIT" stops the build with "License classifiers have been superseded by license expressions".
The file is TOML, a format for settings, and Python 3.11 and later read it with the standard library's tomllib. tomllib.loads() turns TOML text into dictionaries, so you can see what a build tool sees:
import tomllib
text = '''
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "my-cool-lib"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["packaging>=24"]
[project.scripts]
cool-hello = "my_cool_lib.cli:main"
'''
data = tomllib.loads(text)
project = data["project"]
print(project["name"], project["version"])
print(project["dependencies"])
print(project["scripts"])
print(data["build-system"]["build-backend"])
print(sorted(data))
# ✅ Expected output:
# my-cool-lib 0.1.0
# ['packaging>=24']
# {'cool-hello': 'my_cool_lib.cli:main'}
# hatchling.build
# ['build-system', 'project']A dotted table name is a path: [project.scripts] is a table called scripts inside the project table, not a key with a dot in it.
import tomllib
data = tomllib.loads('''
[project]
name = "my-cool-lib"
[project.scripts]
cool-hello = "my_cool_lib.cli:main"
''')
print("project.scripts" in data)
print(data["project"]["scripts"])
# ✅ Expected output:
# False
# {'cool-hello': 'my_cool_lib.cli:main'}TOML isn't Python, and its strings need quotes. A version without them stops the whole file:
import tomllib
tomllib.loads('''
[project]
name = "my-cool-lib"
version = 0.1.0
''')
# ✅ Expected error:
# tomllib.TOMLDecodeError: Expected newline or end of document after a statement (at line 4, column 14)import tomllib
texts = [
'version = "0.1.0"',
'version = 0.1.0',
"version = '0.1.0'",
'dependencies = ["packaging>=24", ]',
'dependencies = ["packaging>=24" "pytest"]',
]
for text in texts:
try:
tomllib.loads(text)
print("ok: ", text)
except tomllib.TOMLDecodeError:
print("not TOML:", text)
# ✅ Expected output:
# ok: version = "0.1.0"
# not TOML: version = 0.1.0
# ok: version = '0.1.0'
# ok: dependencies = ["packaging>=24", ]
# not TOML: dependencies = ["packaging>=24" "pytest"]version = 0.1 is valid TOML, a number, but both build backends refuse it: hatchling with TypeError: Field `project.version` must be a string, and setuptools with configuration error: `project.version` must be string. A version must also follow the rules from Virtual Environments, PEP 440: for 1.0.x, hatchling stops with ValueError: Invalid version `1.0.x` from field `project.version` and setuptools with `project.version` must be pep440.
A table written twice stops the file too:
import tomllib
tomllib.loads('''
[project]
name = "my-cool-lib"
[project]
version = "0.1.0"
''')
# ✅ Expected error:
# tomllib.TOMLDecodeError: Cannot declare ('project',) twice (at line 5, column 9)A misspelt table name is worse, because it's valid TOML. [project.script], one letter short, reads as a table that nothing asks for:
import tomllib
data = tomllib.loads('''
[project]
name = "my-cool-lib"
[project.script]
cool-hello = "my_cool_lib.cli:main"
''')
print(data["project"].get("scripts"))
print(sorted(data["project"]))
# ✅ Expected output:
# None
# ['name', 'script']Measured with that typo, setuptools stopped with configuration error: `project` must not contain {'script'} properties, but hatchling built a wheel without a word, and the wheel had no command in it.
One project, three spellings of its name
As Virtual Environments showed, pip compares project names in lower case, with every run of -, _ and . as one -. File names go the other way: in a wheel's or an sdist's name, each run becomes _, because the file name uses - to separate its parts.
import re
def project_key(name):
return re.sub(r"[-_.]+", "-", name).lower()
def file_prefix(name):
return re.sub(r"[-_.]+", "_", name).lower()
for name in ["my-cool-lib", "My_Cool.Lib", "my__cool--lib"]:
print(f"{name:<14} {project_key(name):<12} {file_prefix(name)}-0.1.0-py3-none-any.whl")
# ✅ Expected output:
# my-cool-lib my-cool-lib my_cool_lib-0.1.0-py3-none-any.whl
# My_Cool.Lib my-cool-lib my_cool_lib-0.1.0-py3-none-any.whl
# my__cool--lib my-cool-lib my_cool_lib-0.1.0-py3-none-any.whlMeasured with both backends, a project with name = "My_Cool.Lib" and version = "1.0-beta" built my_cool_lib-1.0b0.tar.gz and my_cool_lib-1.0b0-py3-none-any.whl: the name as above, and the version in its standard form. The packaging library reads such file names back:
from packaging.utils import canonicalize_name, parse_wheel_filename, parse_sdist_filename
print(canonicalize_name("My_Cool.Lib"))
name, version, build, tags = parse_wheel_filename("my_cool_lib-1.0b0-py3-none-any.whl")
print(name, version, build, sorted(str(t) for t in tags))
print(parse_sdist_filename("my_cool_lib-1.0b0.tar.gz"))
# ✅ Expected output:
# my-cool-lib
# my-cool-lib 1.0b0 () ['py3-none-any']
# ('my-cool-lib', <Version('1.0b0')>)The last part of a wheel's name says where it installs: py3-none-any means any Python 3, with no compiled code, on any system. hatchling wrote py2.py3-none-any instead when requires-python was left out.
Building a wheel and an sdist
The build package builds a project with whatever backend its pyproject.toml names. In a venv, in the project's folder:
python -m pip install build
python -m buildMeasured with build 1.6.1 on Python 3.10 to 3.14, it printed the same lines on each: it made a separate environment, installed hatchling there, built an sdist and then a wheel from the sdist, and ended Successfully built my_cool_lib-0.1.0.tar.gz and my_cool_lib-0.1.0-py3-none-any.whl. Both files are in a new dist folder.
The sdist, short for source distribution, is a .tar.gz of the project: README, pyproject.toml, src and tests, plus a PKG-INFO file. The wheel holds only what gets installed. It's a zip file, and two lines of zipfile list it:
import zipfile
print(zipfile.ZipFile("dist/my_cool_lib-0.1.0-py3-none-any.whl").namelist())For this project, the wheel held eight files:
- my_cool_lib/__init__.py, my_cool_lib/cli.py and my_cool_lib/core.py, the package;
- my_cool_lib-0.1.0.dist-info/METADATA, with lines such as Name: my-cool-lib, Version: 0.1.0, Requires-Python: >=3.10 and Requires-Dist: packaging>=24;
- entry_points.txt in the same folder, which holds [console_scripts] and cool-hello = my_cool_lib.cli:main;
- and WHEEL, licenses/LICENSE and RECORD there too.
The tests, the README and pyproject.toml aren't installed, so they aren't in the wheel.
The package folder needs its __init__.py here. Without one, hatchling stopped with ValueError: Unable to determine which files to ship inside the wheel, while setuptools built a wheel holding the folder as a namespace package, the kind Modules and Packages described.
What installing a wheel leaves behind
python -m pip install dist/my_cool_lib-0.1.0-py3-none-any.whl
cool-hello AdaMeasured in a new venv, pip installed packaging first, since the project needs it, and printed Successfully installed my-cool-lib-0.1.0 packaging-26.3. The venv's site-packages then held a my_cool_lib folder and a my_cool_lib-0.1.0.dist-info folder, and its bin folder a new cool-hello command, which printed Hello, Ada! and ended with exit status 0. That command is a small script pip writes: it imports main from my_cool_lib.cli and passes its return value to sys.exit(), so main()'s return value is the command's exit status.
This site's editor has no pip. To inspect the metadata boundary, this example makes a partial distribution fixture in a ZIP archive, unpacks it into site, and adds that folder to sys.path. It intentionally omits the required WHEEL and RECORD files, so it is not an installable wheel and does not replace a build or pip. importlib.metadata reads its version, requirements and entry point, whose function we then call directly:
import sys
import zipfile
from importlib.metadata import entry_points, requires, version
files = {
"my_cool_lib/__init__.py": "from .core import say_hello\n",
"my_cool_lib/core.py": "def say_hello(name):\n return f'Hello, {name}!'\n",
"my_cool_lib/cli.py": "from .core import say_hello\n\ndef main():\n print(say_hello('command line'))\n return 0\n",
"my_cool_lib-0.1.0.dist-info/METADATA": "Metadata-Version: 2.4\nName: my-cool-lib\nVersion: 0.1.0\nRequires-Dist: packaging>=24\n",
"my_cool_lib-0.1.0.dist-info/entry_points.txt": "[console_scripts]\ncool-hello = my_cool_lib.cli:main\n",
}
with zipfile.ZipFile("metadata-fixture.zip", "w") as wheel:
for name, text in files.items():
wheel.writestr(name, text)
with zipfile.ZipFile("metadata-fixture.zip") as wheel:
print(wheel.namelist()[-2:])
wheel.extractall("site")
sys.path.insert(0, "site")
print(version("my-cool-lib"), requires("my-cool-lib"))
[command] = [ep for ep in entry_points(group="console_scripts") if ep.name == "cool-hello"]
print(command.value)
main = command.load()
print("exit code", main())
sys.path.remove("site")
# ✅ Expected output:
# ['my_cool_lib-0.1.0.dist-info/METADATA', 'my_cool_lib-0.1.0.dist-info/entry_points.txt']
# 0.1.0 ['packaging>=24']
# my_cool_lib.cli:main
# Hello, command line!
# exit code 0For the direct wheel-file installation shown here, pip also writes INSTALLER, REQUESTED and direct_url.json into the .dist-info folder, and the command script. But what version() and entry_points() read is the same. version() accepts any spelling of the project's name:
import sys
import zipfile
from importlib.metadata import version
with zipfile.ZipFile("metadata-fixture.zip", "w") as wheel:
wheel.writestr("my_cool_lib/__init__.py", "")
wheel.writestr("my_cool_lib-0.1.0.dist-info/METADATA", "Metadata-Version: 2.4\nName: my-cool-lib\nVersion: 0.1.0\n")
with zipfile.ZipFile("metadata-fixture.zip") as wheel:
wheel.extractall("site")
sys.path.insert(0, "site")
for name in ["my-cool-lib", "my_cool_lib", "My.Cool-Lib"]:
print(name, version(name))
sys.path.remove("site")
# ✅ Expected output:
# my-cool-lib 0.1.0
# my_cool_lib 0.1.0
# My.Cool-Lib 0.1.0An entry point is text, module:function, and nothing checks the function's name until the command runs:
import sys
import zipfile
from importlib.metadata import entry_points
with zipfile.ZipFile("entrypoint-fixture.zip", "w") as wheel:
wheel.writestr("demo_cli/__init__.py", "def main():\n return 0\n")
wheel.writestr("demo_cli-1.0.dist-info/METADATA", "Metadata-Version: 2.4\nName: demo-cli\nVersion: 1.0\n")
wheel.writestr("demo_cli-1.0.dist-info/entry_points.txt", "[console_scripts]\ndemo = demo_cli:launch\n")
with zipfile.ZipFile("entrypoint-fixture.zip") as wheel:
wheel.extractall("site")
sys.path.insert(0, "site")
try:
[command] = [ep for ep in entry_points(group="console_scripts") if ep.name == "demo"]
print(command.value)
command.load()
finally:
sys.path.remove("site")
# ✅ Expected output:
# demo_cli:launch
# ✅ Expected error:
# AttributeError: module 'demo_cli' has no attribute 'launch'Measured with a real project, a typo, cool-hello = "my_cool_lib.cli:mian", built and installed with both backends, and running cool-hello then stopped with ImportError: cannot import name 'mian' from 'my_cool_lib.cli' and exit status 1. Leaving out the colon, "my_cool_lib.cli.main", was caught sooner: pip refused to install the wheel, saying Invalid script entry point and A callable suffix is required.
pip also acts on requires-python. With requires-python = ">=3.12", installing on Python 3.11 stopped with ERROR: Package 'my-cool-lib' requires a different Python: 3.11.15 not in '>=3.12'.
Optional dependencies go in a table of their own, each group under a name of your choosing, an extra:
[project.optional-dependencies]
cli = ["rich>=13"]python -m pip install "my-cool-lib[cli]", in quotes for the shell's sake, then installed rich and the three packages it needs, while a plain install left them out.
pip install -e: work on a project while it's installed
Installing a wheel copies your code into site-packages, so an edit to src changes nothing until you build and install again. An editable install, made with -e from the project's folder, points Python at src instead:
python -m pip install -e .This was measured with setuptools as the backend; hatchling's editable install also needs a package called editables, which pip installs into the build's environment. pip put a file called __editable__.my_cool_lib-0.1.0.pth into site-packages, holding the full path of the project's src folder. Python reads such .pth files when it starts, and adds the folders they name to sys.path. pip freeze listed the project as -e and its folder, and import my_cool_lib worked from any folder.
Code changes show at once. With "Hello" changed to "Hi" in core.py, the editable install's cool-hello printed Hi, command line!, while a normal install of the same project still printed Hello, command line!. But the metadata was written when pip ran: after the version in pyproject.toml went from 0.1.0 to 0.2.0, version("my-cool-lib") still said 0.1.0. So after you change pyproject.toml (the version, the dependencies or the commands), run python -m pip install -e . again. Here is the same effect in miniature:
import sys
from importlib.metadata import version
from pathlib import Path
Path("site/my_cool_lib").mkdir(parents=True, exist_ok=True)
Path("site/my_cool_lib/__init__.py").write_text("")
Path("site/my_cool_lib-0.1.0.dist-info").mkdir(exist_ok=True)
Path("site/my_cool_lib-0.1.0.dist-info/METADATA").write_text("Metadata-Version: 2.4\nName: my-cool-lib\nVersion: 0.1.0\n")
Path("pyproject.toml").write_text('[project]\nname = "my-cool-lib"\nversion = "0.2.0"\n')
sys.path.insert(0, "site")
print(version("my-cool-lib"))
sys.path.remove("site")
# ✅ Expected output:
# 0.1.0An editable install is also how tests import the project: Testing with pytest: Fixtures, Parametrisation & Mocks runs tests like tests/test_core.py, which imports my_cool_lib as any user would.
Checking and uploading with twine
Uploading is done with twine, which you install like build. twine check looks over the built files first, then twine upload sends them, to TestPyPI, a separate index for practice, or to PyPI itself:
python -m pip install twine
twine check dist/*
twine upload --repository testpypi dist/*
twine upload dist/*For this lesson's project, twine check printed PASSED for each of the two files. No upload was made for this lesson, so what an upload prints isn't shown here. What twine 7.0.0's own code says about it:
- testpypi is built in, at https://test.pypi.org/legacy/, so the first upload command needs no settings file.
- On PyPI and TestPyPI the user name is __token__, filled in for you, and twine asks Enter your API token:. A comment in its code says "As of 2024-01-01, PyPI requires API tokens for uploads." The token comes from your PyPI account; keep it out of your code and your repository.
- "If a package already exists on the repository, most repositories will return an error response." So a changed file can't simply be uploaded again under the same name: a corrected release goes out under a new version number, which gives its files new names.
TestPyPI is separate from PyPI, so it may not hold the packages yours depends on. Measured offline, installing from a package index without packaging stopped with ERROR: Could not find a version that satisfies the requirement packaging>=24 (from my-cool-lib).
Practice: work out the file names
Fill in the three blanks so the program reads the name and version from pyproject.toml and prints the two file names a build makes for them. The hints under the code give each one.
import re
import tomllib
from packaging.version import Version
pyproject = tomllib.loads('''
[project]
name = "My_Cool.Lib"
version = "1.0-beta"
''')
project = pyproject["___"]
name = re.sub(r"[-_.]+", "___", project["name"]).lower()
version = Version(project["___"])
print(f"{name}-{version}-py3-none-any.whl")
print(f"{name}-{version}.tar.gz")
# 👉 replace ___ with project
# 👉 replace ___ with _
# 👉 replace ___ with version
# ✅ Expected output:
# my_cool_lib-1.0b0-py3-none-any.whl
# my_cool_lib-1.0b0.tar.gzOn your own: check a pyproject.toml before building
Write check(text). It reads pyproject text with tomllib and returns a list of selected problems a build or an install would stop on: a missing name or version, a version that is not a string or that Version() rejects, a dependency that Requirement() can't read, and a script whose target has no colon. It returns ["ok"] when there are none. Run it on a good and a bad pyproject.
This small checker assumes a project table, a list of dependency strings and a scripts table of string targets. Malformed TOML still raises its parsing error. An ok result covers only the listed checks: a real backend validates the full schema, and installing and running the package tests whether its entry points and imports work.
import tomllib
from packaging.requirements import InvalidRequirement, Requirement
from packaging.version import InvalidVersion, Version
def check(text):
project = tomllib.loads(text).get("project", {})
problems = []
for key in ("name", "version"):
if key not in project:
problems.append(f"missing {key}")
if "version" in project and not isinstance(project["version"], str):
problems.append("version must be a string")
elif "version" in project:
try:
Version(project["version"])
except InvalidVersion:
problems.append(f"version {project['version']!r} is not a valid version")
for dep in project.get("dependencies", []):
try:
Requirement(dep)
except InvalidRequirement:
problems.append(f"dependency {dep!r} can't be read")
for command, target in project.get("scripts", {}).items():
if ":" not in target:
problems.append(f"script {command!r} needs module:function")
return problems or ["ok"]
good = '''
[project]
name = "my-cool-lib"
version = "0.1.0"
dependencies = ["packaging>=24"]
[project.scripts]
cool-hello = "my_cool_lib.cli:main"
'''
bad = '''
[project]
name = "my-cool-lib"
version = "1.0.x"
dependencies = ["packaging>=24,<", "rich"]
[project.scripts]
cool-hello = "my_cool_lib.cli.main"
'''
for text in (good, bad):
for line in check(text):
print(line)
print("--")
print(check('[project]\nname = "demo"\nversion = 0.1'))
# ✅ Expected output:
# ok
# --
# version '1.0.x' is not a valid version
# dependency 'packaging>=24,<' can't be read
# script 'cool-hello' needs module:function
# --
# ['version must be a string']
Practice quiz
TOML text holding a [project.scripts] table, with cool-hello = "my_cool_lib.cli:main" under it, is read with data = tomllib.loads(text). What does print(list(data), list(data["project"])) print?
- ['project.scripts'] []
- ['project'] ['scripts']
- ['project', 'scripts'] []
- It stops: [project] was never written
Answer: ['project'] ['scripts']. A dotted table name is a path: [project.scripts] is a table called scripts inside a table called project, which TOML creates on the way.
pyproject.toml says name = "My_Cool.Lib" and version = "1.0-beta". What is the wheel's file called?
- My_Cool.Lib-1.0-beta-py3-none-any.whl
- my-cool-lib-1.0-beta-py3-none-any.whl
- my_cool_lib-1.0-beta-py3-none-any.whl
- my_cool_lib-1.0b0-py3-none-any.whl
Answer: my_cool_lib-1.0b0-py3-none-any.whl. Both build tools turn each run of -, _ and . in the name into _, lower-case it, and write the version in its standard form, 1.0b0.
What does tomllib.loads() do with the line version = 0.1.0, without quotes?
- It stops with TOMLDecodeError: Expected newline or end of document after a statement
- It reads the string '0.1.0'
- It reads the number 0.1
- It stops with a SyntaxError
Answer: It stops with TOMLDecodeError: Expected newline or end of document after a statement. 0.1 alone would be a number, a float, but the second dot leaves TOML unable to read the rest of the line. A version is a string, so it goes in quotes.
You install your project with pip install -e ., then change version in pyproject.toml from 0.1.0 to 0.2.0. What does importlib.metadata.version("my-cool-lib") give?
- 0.2.0
- It stops with PackageNotFoundError
- 0.1.0, until pip install -e . runs again
- None
Answer: 0.1.0, until pip install -e . runs again. An editable install points Python at your code, but the metadata, version included, was written when pip ran. Changes to pyproject.toml need another pip install -e .
[project.scripts] says cool-hello = "my_cool_lib.cli:mian", a typo for main. When does it fail?
- Only when you run cool-hello, with ImportError: cannot import name 'mian'
- The build stops
- pip refuses to install it
- Never: Python finds main
Answer: Only when you run cool-hello, with ImportError: cannot import name 'mian'. The text is never checked against your code: the build and the install succeed, and the command fails when it imports the name.
In a src-layout project that isn't installed, you run python -c "import my_cool_lib" from the project folder. What happens?
- It imports the copy in src
- ImportError: attempted relative import with no known parent package
- It works from Python 3.12 on
- ModuleNotFoundError: No module named 'my_cool_lib'
Answer: ModuleNotFoundError: No module named 'my_cool_lib'. Python looks in the current folder, not in src, so the package can't be found until the project is installed.
pyproject.toml says requires-python = ">=3.12". What happens when you pip install the wheel with Python 3.11?
- It installs, and fails when imported
- It installs with a warning
- pip refuses: Package 'my-cool-lib' requires a different Python
- pip installs Python 3.12 first
Answer: pip refuses: Package 'my-cool-lib' requires a different Python. requires-python is a version specifier that pip checks before it installs anything.
Which of these files is not in the wheel that python -m build made for this lesson's project?
- my_cool_lib/cli.py
- tests/test_core.py
- my_cool_lib-0.1.0.dist-info/METADATA
- my_cool_lib-0.1.0.dist-info/entry_points.txt
Answer: tests/test_core.py. A wheel holds what gets installed: the package and its .dist-info folder. The tests, the README and pyproject.toml go in the sdist.
Continue this course
- Previous: Virtual Environments & Dependency Management Best Practices
- Next: Working with Files, Streams & Large Datasets — Handle large files with streaming, chunking, and pathlib
- Quick reference: Python cheat sheet
Frequently asked questions
Should I use hatchling or setuptools?
Either builds this lesson's project, and both put the same files into its wheel. Differences measured with hatchling 1.32.4 and setuptools 84.0.0: a missing README stops hatchling with OSError: Readme file does not exist: README.md, where setuptools only warns; a License classifier next to license = "MIT" stops setuptools; a file such as data/greetings.json inside the package folder went into hatchling's wheel but not setuptools'; and [project.script], one letter short, stops setuptools, while hatchling builds a wheel with no command.
Do I still need setup.py?
Not for a project like this one: both build tools here worked from pyproject.toml alone. In a folder with neither file, python -m build stops and says it found "no pyproject.toml or setup.py".
Can the version number live in my code?
Yes. Write dynamic = ["version"] under [project] instead of a version, and tell the build tool where to read it. For hatchling that's a [tool.hatch.version] table with path = "src/my_cool_lib/__init__.py", and for setuptools a [tool.setuptools.dynamic] table with version = {attr = "my_cool_lib.__version__"}. With __version__ = "0.3.0" in __init__.py, both built my_cool_lib-0.3.0-py3-none-any.whl.
What is a py.typed file for?
An empty file called py.typed in the package folder says the package's type hints are meant to be checked. mypy 1.19.1, checking a program that called say_hello(42), first stopped at the import, saying the package was "missing library stubs or py.typed marker". With py.typed in the installed package, it reported the real mistake: Argument 1 to "say_hello" has incompatible type "int"; expected "str". Type Hints & Static Typing with mypy covers mypy itself.
Why isn't my data file in the installed package?
Build tools choose the files differently. With no extra settings, a data/greetings.json inside the package folder went into hatchling's wheel but not setuptools'. List the wheel's files with zipfile before you publish, as shown in this lesson.
Can this site's editor build or install a package?
No: it has no pip, no build tool and no terminal. Its ZIP examples are deliberately partial distribution metadata fixtures, not installable wheels; a real wheel needs a build backend and the required wheel metadata.