Sub topic 9
Packaging code and defining command-line entry points
This chapter shows how a uv project becomes an installable package and how pyproject.toml exposes a function as a terminal command. It assumes you can run uv init, uv add, and uv run, and that you know what a Python module and an import are. Build backends and uv build come in the next chapter.
Why package your code
A project that is not a package is a folder of scripts. You run them from that folder, and imports work only because of the current directory. A package is code that an installer can place into an environment. Once it is installed, import weather_cli works from anywhere, and the installer can create commands on your PATH.
uv init --package weather-cli creates a packaged project. Plain uv init creates an application layout, which has no [build-system] table. The difference is the build system that makes the project installable.
weather-cli/
├── pyproject.toml
├── README.md
├── .python-version
└── src/
└── weather_cli/
└── __init__.pyThis is the src layout. The importable package sits under src/, so the repository root is not on the import path by accident. Tests therefore import the installed package, not a stray copy next to them. A missing file or a wrong package name shows up as an error in your own environment, not on a user's machine.
Naming: distribution versus import package
Two names are involved, and they follow different rules.
| Name | Where it appears | Example | Rule |
|---|---|---|---|
| Distribution name | `name` in `[project]`, `uv add`, PyPI | `weather-cli` | Hyphens, dots, and underscores are treated as equal. |
| Import name | The directory under `src/`, `import` statements | `weather_cli` | Must be a valid Python identifier, so no hyphens. |
uv and hatchling derive the import name from the distribution name by replacing hyphens with underscores. If you rename one without the other, the build backend may not find your package.
Declaring a command-line entry point
The [project.scripts] table maps a command name to a Python callable.
[project]
name = "weather-cli"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["httpx>=0.27", "typer>=0.12"]
[project.scripts]
weather = "weather_cli:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"Each entry has the form command = "module.path:callable". The text before the colon is an importable module, and the text after it is a name inside that module. Here weather_cli:main means "import weather_cli, then take its main attribute". A dotted module path such as weather_cli.cli:main points into a submodule.
The matching code in src/weather_cli/__init__.py:
import typer
def main() -> None:
typer.echo("Sunny")
if __name__ == "__main__":
typer.run(main)The if __name__ block lets you run the file directly during development. The installed command never uses it. It imports the module and calls main() itself.
What happens when you sync
The command does not exist until the project is installed into the environment. uv installs a project into its environment in editable mode, and the installer writes a small launcher file into the environment's bin directory (Scripts on Windows).
uv sync
uv run weatheruv run syncs first, so a bare uv run weather also works. If you change [project.scripts] later, uv run notices that the project metadata changed and reinstalls. Running uv sync yourself does the same.
The launcher is roughly "import the module, then sys.exit(main())". That last step matters in practice, as the next section shows.
Writing a good entry-point function
The callable is called with no arguments. This has three consequences.
- Read arguments yourself. A function with required parameters fails with a
TypeError. Usesys.argv,argparse, or a framework that readssys.argvfor you. - The return value is the exit code.
Noneand0mean success. An integer sets the exit status. Any other value is printed to stderr, and the exit code is 1. - Importing the module should be cheap. The launcher imports your module on every run, so keep slow work out of module level.
A plain argparse version shows the pattern without a framework:
import argparse
import sys
def main() -> int:
parser = argparse.ArgumentParser(prog="weather")
parser.add_argument("city")
args = parser.parse_args()
if args.city == "Atlantis":
print("Unknown city", file=sys.stderr)
return 1
print(f"{args.city}: Sunny")
return 0With Typer you often have an app object, not a function. The entry point can then point at the object, because Typer apps are callable:
import typer
app = typer.Typer()
@app.command()
def show(city: str) -> None:
typer.echo(f"{city}: Sunny")The entry would be weather = "weather_cli:app".
Running a package as a module
Add src/weather_cli/__main__.py to support python -m weather_cli or uv run python -m weather_cli:
from weather_cli import main
if __name__ == "__main__":
main()This is useful when you want a command that works without relying on the launcher being on PATH.
Other entry point tables
[project.scripts] is for console commands. Two related tables exist.
[project.gui-scripts]has the same format. On Windows, its launchers do not open a console window.[project.entry-points."group.name"]registers a plugin under an arbitrary group. Another program, such as pytest, finds it withimportlib.metadata.entry_points(group="...").
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Failed to spawn: weather`, or command not found | The project was not installed because there is no `[build-system]` | Add one, or run `uv init --package` for new projects. Then run `uv sync`. |
| `ModuleNotFoundError: No module named 'weather-cli'` | A hyphen in the entry point module path | Use the import name: `weather_cli:main`. |
| `ImportError: cannot import name 'main'` | The attribute after the colon is missing from the module | Check spelling, and check that the function is defined at module level. |
| `TypeError: main() missing 1 required positional argument` | The function takes parameters | Read arguments inside the function or use a framework. |
| The command prints an old message after an edit | An old non-editable install | Run `uv sync --reinstall-package weather-cli`. |
| The shell cannot find `weather` outside `uv run` | The environment is not active | Run `uv run weather`, or activate `.venv`. |
Checking the result
A quick way to confirm the wiring is to ask the environment what it knows:
uv run weather
uv run python -c "from importlib.metadata import entry_points; print(entry_points(group='console_scripts')['weather'])"The second command prints the entry point as weather_cli:main. The same data is what the launcher uses, so a mismatch here points to the cause.
Exercise
You add [project.scripts] with report = "weather_cli.report:run" to a project created with plain uv init, and uv run report reports that the command is not found. Name the missing piece and give two other things to check.
Show answer
Plain uv init creates an application without a [build-system] table, so uv does not install the project and no launcher is generated. Add a build system (for example hatchling) or recreate the project with uv init --package, then run uv sync. Also check that the file src/weather_cli/report.py exists, and that it defines a module-level function named run that takes no required arguments.
Exercise
Your main() returns the string "no data". What does the installed command do?
Show answer
The launcher passes the return value to sys.exit(). A string is printed to stderr and the process exits with status 1. To return a specific status, return an integer such as 2.