hoangquochung1110 / public-notes

0 stars 0 forks source link

How to package a python project using uv #2

Open hoangquochung1110 opened 3 months ago

hoangquochung1110 commented 3 months ago
PROJECT_NAME = 
uv init --lib $PROJECT_NAME
hoangquochung1110 commented 3 months ago

Required dependencies

uv add <dependency>

Dependencies for development

uv add --dev <dependency> 
hoangquochung1110 commented 3 months ago

Project structure would look like this:

Image

hoangquochung1110 commented 3 months ago

Init virtual env and use

uv venv .venv --python 3.12
source .venv/bin/activate
hoangquochung1110 commented 3 months ago

Use Makefile to manage distribution

# A Makefile is not required, but can be helpful for organizing the actions
# needed when working on a project.

.PHONY: help clean tools dist test_pypi pypi

.DEFAULT_GOAL := help

help:   ## Display this help message.
    @echo "Please use \`make <target>' where <target> is one of:"
    @awk -F ':.*?## ' '/^[a-zA-Z]/ && NF==2 {printf "  %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST) | sort

clean:  ## Remove stuff we don't need.
    # __pycache__ is where Python puts compiled code: *.pyc files.
    find . -name '__pycache__' -exec rm -rf {} +
    # build, dist, and .egg-info are directories made when building distributions.
    rm -fr build/ dist/ src/*.egg-info

tools:  ## Install the development tools.
    python -m pip install -r dev-requirements.txt

dist:   ## Build the distributions.
    uv build
test_pypi: ## Upload the distributions to PyPI's testing server.
    python -m twine upload --verbose --repository testpypi dist/*

pypi: ## Upload the built distributions to PyPI.
    python -m twine upload --verbose dist/*
hoangquochung1110 commented 3 months ago

Local testing

uv run pip install -e .

Now we can open Python REPL and import things to see how it works

from example_lib import hello
hello()
hoangquochung1110 commented 3 months ago

For other projects to consume the package

make dist

By default, make dist - a wrapper of uv build will build the project in the current directory, and place the built artifacts in a dist/ subdirectory:

❯ ls dist                
example_lib-0.1.0-py3-none-any.whl example_lib-0.1.0.tar.gz

Install it in other projects flag --force-reinstall is optional, helpful when we make some edition to the package until we make it right

pip install /path/to/dist/example_lib-0.1.0-py3-none-any.whl --force-reinstall