Skip to content
Myr

:memo: Add docs section, build a package from scratch (#71)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* :memo: Add docs section, build a package from scratch * :memo: Update Package docs * :pencil2: Fix internal links

authored by Sebastián Ramírez · committed by GitHub · parent 150baa2 · Browse files · 3 files+644 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+644 added−1 removed

  • other:+644 added−1 removed

3 files+644 added−1 removed

added:docs/tutorial/package.md+642 added
1When you create a CLI program with **Typer** you probably want to create your own Python package.23That's what allows your users to install it and have it as an independent program that they can use in their terminal.45And that's also required for shell auto completion to work (unless you use your program through [Typer CLI](../typer-cli.md){.internal-link target=_blank}).67Nowadays, there are several ways and tools to create Python packages (what you install with `pip install something`).89You might even have your favorite already.1011Here's a very opinionated, short guide, showing one of the alternative ways of creating a Python package with a **Typer** app, from scratch.1213!!! tip14 If you already have a favorite way of creating Python packages, feel free to skip this.1516## Prerequisites1718For this guide we'll use <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a>.1920Poetry's docs are great, so go ahead, check them and install it.2122## Create a project2324Let's say we want to create a CLI application called `portal-gun`.2526To make sure your package doesn't collide with the package created by someone else, we'll name it with a prefix of your name.2728So, if your name is Rick, we'll call it `rick-portal-gun`.2930Create a project with Poetry:3132<div class="termy">3334```console35$ poetry new rick-portal-gun3637Created package rick_portal_gun in rick-portal-gun3839// Enter the new project directory40cd ./rick-portal-gun41```4243</div>4445## Dependencies and environment4647Add `typer[all]` to your dependencies:4849<div class="termy">5051```console52$ poetry add typer[all]5354// It creates a virtual environment for your project55Creating virtualenv rick-portal-gun-w31dJa0b-py3.6 in /home/rick/.cache/pypoetry/virtualenvs56Using version ^0.1.0 for typer5758Updating dependencies59Resolving dependencies... (1.2s)6061Writing lock file6263---> 100%6465Package operations: 15 installs, 0 updates, 0 removals6667 - Installing zipp (3.1.0)68 - Installing importlib-metadata (1.5.0)69 - Installing pyparsing (2.4.6)70 - Installing six (1.14.0)71 - Installing attrs (19.3.0)72 - Installing click (7.1.1)73 - Installing colorama (0.4.3)74 - Installing more-itertools (8.2.0)75 - Installing packaging (20.3)76 - Installing pluggy (0.13.1)77 - Installing py (1.8.1)78 - Installing shellingham (1.3.2)79 - Installing wcwidth (0.1.8)80 - Installing pytest (5.4.1)81 - Installing typer (0.0.11)8283// Activate that new virtual environment84$ poetry shell8586Spawning shell within /home/rick/.cache/pypoetry/virtualenvs/rick-portal-gun-w31dJa0b-py3.68788// Open an editor using this new environment, for example VS Code89$ code ./90```9192</div>9394You can see that you have a generated project structure that looks like:9596```97.98├── poetry.lock99├── pyproject.toml100├── README.rst101├── rick_portal_gun102│   └── __init__.py103└── tests104 ├── __init__.py105 └── test_rick_portal_gun.py106```107108## Create your app109110Now let's create an extremely simple **Typer** app.111112Create a file `rick_portal_gun/main.py` with:113114```Python115import typer116117118app = typer.Typer()119120121@app.callback()122def callback():123 """124 Awesome Portal Gun125 """126127128@app.command()129def shoot():130 """131 Shoot the portal gun132 """133 typer.echo("Shooting portal gun")134135136@app.command()137def load():138 """139 Load the portal gun140 """141 typer.echo("Loading portal gun")142```143144!!! tip145 As we are creating an installable Python package, there's no need to add a section with `if __name__ == "__main__:`.146147## Modify the README148149Let's change the README. By default it's a file `README.rst`.150151Let's change it to `README.md`. So, change the extension from `.rst` to `.md`.152153So that we can use Markdown instead of reStructuredText.154155And change the file to have something like:156157```Markdown158# Portal Gun159160The awesome Portal Gun161```162163## Modify your project metadata164165Edit your file `pyproject.toml`.166167It would look something like:168169```TOML170[tool.poetry]171name = "rick-portal-gun"172version = "0.1.0"173description = ""174authors = ["Rick Sanchez <rick@example.com>"]175176[tool.poetry.dependencies]177python = "^3.6"178typer = {extras = ["all"], version = "^0.1.0"}179180[tool.poetry.dev-dependencies]181pytest = "^5.2"182183[build-system]184requires = ["poetry>=0.12"]185build-backend = "poetry.masonry.api"186```187188We changed the default README, so let's make it use the new `README.md`.189190Add the line:191192```TOML hl_lines="6"193[tool.poetry]194name = "rick-portal-gun"195version = "0.1.0"196description = ""197authors = ["Rick Sanchez <rick@example.com>"]198readme = "README.md"199200[tool.poetry.dependencies]201python = "^3.6"202typer = {extras = ["all"], version = "^0.1.0"}203204[tool.poetry.dev-dependencies]205pytest = "^5.2"206207[build-system]208requires = ["poetry>=0.12"]209build-backend = "poetry.masonry.api"210```211212## Add a "script"213214We are creating a Python package that can be installed with `pip install`.215216But we want it to provide a CLI program that can be executed in the shell.217218To do that, we add a configuration to the `pyproject.toml` in the section `[tool.poetry.scripts]`:219220```TOML hl_lines="8 9"221[tool.poetry]222name = "rick-portal-gun"223version = "0.1.0"224description = ""225authors = ["Rick Sanchez <rick@example.com>"]226readme = "README.md"227228[tool.poetry.scripts]229rick-portal-gun = "rick_portal_gun.main:app"230231[tool.poetry.dependencies]232python = "^3.6"233typer = {extras = ["all"], version = "^0.1.0"}234235[tool.poetry.dev-dependencies]236pytest = "^5.2"237238[build-system]239requires = ["poetry>=0.12"]240build-backend = "poetry.masonry.api"241```242243Here's what that line means:244245`rick-portal-gun`: will be the name of the CLI program. That's how we will call it in the terminal once it is installed. Like:246247<div class="termy">248249```console250$ rick-portal-gun251252// Something happens here ✨253```254255</div>256257`rick_portal_gun.main`, in the part `"rick_portal_gun.main:app"`, with underscores, refers to the Python module to import. That's what someone would use in a section like:258259```Python260from rick_portal_gun.main import # something goes here261```262263The `app` in `"rick_portal_gun.main:app"` is the thing to import from the module, and to call as a function, like:264265```Python266from rick_portal_gun.main import app267app()268```269270That config section tells Poetry that when this package is installed we want it to create a command line program called `rick-portal-gun`.271272And that the object to call (like a function) is the one in the variable `app` inside of the module `rick_portal_gun.main`.273274## Install your package275276That's what we need to create a package.277278You can now install it:279280<div class="termy">281282```console283$ poetry install284285Installing dependencies from lock file286287No dependencies to install or update288289 - Installing rick-portal-gun (0.1.0)290```291292</div>293294## Try your CLI program295296Your package is installed in the environment created by Poetry, but you can already use it.297298<div class="termy">299300```console301// You can use the which program to check which rick-portal-gun program is available (if any)302$ which rick-portal-gun303304// You get the one from your environment305/home/rick/.cache/pypoetry/virtualenvs/rick-portal-gun-w31dJa0b-py3.6/bin/rick-portal-gun306307// Try it308$ rick-portal-gun309310// You get all the standard help311Usage: rick-portal-gun [OPTIONS] COMMAND [ARGS]...312313 Awesome Portal Gun314315Options:316 --install-completion Install completion for the current shell.317 --show-completion Show completion for the current shell, to copy it or customize the installation.318319 --help Show this message and exit.320321Commands:322 load Load the portal gun323 shoot Shoot the portal gun324```325326</div>327328## Create a wheel package329330Python packages have a standard format called a "wheel". It's a file that ends in `.whl`.331332You can create a wheel with Poetry:333334<div class="termy">335336```console337$ poetry build338339Building rick-portal-gun (0.1.0)340 - Building sdist341 - Built rick-portal-gun-0.1.0.tar.gz342343 - Building wheel344 - Built rick_portal_gun-0.1.0-py3-none-any.whl345```346347</div>348349After that, if you check in your project directory, you should now have a couple of extra files at `./dist/`:350351``` hl_lines="3 4"352.353├── dist354│   ├── rick_portal_gun-0.1.0-py3-none-any.whl355│   └── rick-portal-gun-0.1.0.tar.gz356├── pyproject.toml357├── README.md358├── ...359```360361The `.whl` is the wheel file. You can send that wheel file to anyone and they can use it to install your program (we'll see how to upload it to PyPI in a bit).362363## Test your wheel package364365Now you can open another terminal and install that package from the file for your own user with:366367<div class="termy">368369```console370$ pip install --user /home/rock/code/rick-portal-gun/dist/rick_portal_gun-0.1.0-py3-none-any.whl371372---> 100%373```374375</div>376377!!! warning378 The `--user` is important, that ensures you install it in your user's directory and not in the global system.379380 If you installed it in the global system (e.g. with `sudo`) you could install a version of a library (e.g. a sub-dependency) that is incompatible with your system.381382!!! tip383 Bonus points if you use <a href="https://github.com/pipxproject/pipx" class="external-link" target="_blank">`pipx`</a> to install it while keeping an isolated environment for your Python CLI programs 🚀384385Now you have your CLI program installed. And you can use it freely:386387<div class="termy">388389```console390$ rick-portal-gun shoot391392// It works 🎉393Shooting portal gun394```395396</div>397398Having it installed globally (and not in a single environment), you can now install completion globally for it:399400<div class="termy">401402```console403$ rick-portal-gun --install-completion404405zsh completion installed in /home/user/.zshrc.406Completion will take effect once you restart the terminal.407```408409</div>410411!!! tip412 If you want to remove completion you can just delete the added line in that file.413414And after you restart the terminal you will get completion for your new CLI program:415416<div class="termy">417418```console419$ rick-portal-gun [TAB][TAB]420421// You get completion for your CLI program ✨422load -- Load the portal gun423shoot -- Shoot the portal gun424```425426</div>427428## Publish to PyPI (optional)429430You can publish that new package to <a href="https://pypi.org/" class="external-link" target="_blank">PyPI</a> to make it public, so others can install it easily.431432So, go ahead and create an account there (it's free).433434### PyPI API token435436To do it, you first need to configure a PyPI auth token.437438Login to <a href="https://pypi.org/" class="external-link" target="_blank">PyPI</a>.439440And then go to <a href="https://pypi.org/manage/account/token/" class="external-link" target="_blank">https://pypi.org/manage/account/token/</a> to create a new token.441442Let's say your new API token is:443444```445pypi-wubalubadubdub-deadbeef1234446```447448Now configure Poetry to use this token with the command `poetry config pypi-token.pypi`:449450<div class="termy">451452```console453$ poetry config pypi-token.pypi pypi-wubalubadubdub-deadbeef1234454// It won't show any output, but it's already configured455```456457</div>458459### Publish to PyPI460461Now you can publish your package with Poetry.462463You could build the package (as we did above) and then publish later, or you could tell poetry to build it before publishing in one go:464465<div class="termy">466467```console468$ poetry publish --build469470# There are 2 files ready for publishing. Build anyway? (yes/no) [no] $ yes471472---> 100%473474Building rick-portal-gun (0.1.0)475 - Building sdist476 - Built rick-portal-gun-0.1.0.tar.gz477478 - Building wheel479 - Built rick_portal_gun-0.1.0-py3-none-any.whl480481Publishing rick-portal-gun (0.1.0) to PyPI482 - Uploading rick-portal-gun-0.1.0.tar.gz 100%483 - Uploading rick_portal_gun-0.1.0-py3-none-any.whl 100%484```485486</div>487488Now you can go to PyPI and check your projects at <a href="https://pypi.org/manage/projects/" class="external-link" target="_blank">https://pypi.org/manage/projects/</a>.489490You should now see your new "rick-portal-gun" package.491492### Install from PyPI493494Now to see that we can install it form PyPI, open another terminal, and uninstall the currently installed package.495496<div class="termy">497498```console499$ pip uninstall rick-portal-gun500501Found existing installation: rick-portal-gun 0.1.0502Uninstalling rick-portal-gun-0.1.0:503 Would remove:504 /home/user/.local/bin/rick-portal-gun505 /home/user/.local/lib/python3.6/site-packages/rick_portal_gun-0.1.0.dist-info/*506 /home/user/.local/lib/python3.6/site-packages/rick_portal_gun/*507# Proceed (y/n)? $ y508 Successfully uninstalled rick-portal-gun-0.1.0509```510511</div>512513And now install it again, but this time using just the name, so that `pip` pulls it from PyPI:514515<div class="termy">516517```console518$ pip install --user rick-portal-gun519520// Notice that it says "Downloading" 🚀521Collecting rick-portal-gun522 Downloading rick_portal_gun-0.1.0-py3-none-any.whl (1.8 kB)523Requirement already satisfied: typer[all]<0.0.12,>=0.0.11 in ./.local/lib/python3.6/site-packages (from rick-portal-gun) (0.0.11)524Requirement already satisfied: click<7.2.0,>=7.1.1 in ./anaconda3/lib/python3.6/site-packages (from typer[all]<0.0.12,>=0.0.11->rick-portal-gun) (7.1.1)525Requirement already satisfied: colorama; extra == "all" in ./anaconda3/lib/python3.6/site-packages (from typer[all]<0.0.12,>=0.0.11->rick-portal-gun) (0.4.3)526Requirement already satisfied: shellingham; extra == "all" in ./anaconda3/lib/python3.6/site-packages (from typer[all]<0.0.12,>=0.0.11->rick-portal-gun) (1.3.1)527Installing collected packages: rick-portal-gun528Successfully installed rick-portal-gun-0.1.0529```530531</div>532533And now test the newly installed package from PyPI:534535<div class="termy">536537```console538$ rick-portal-gun load539540// It works! 🎉541Loading portal gun542```543544</div>545546## Generate docs with **Typer CLI** (optional)547548You can install and use [Typer CLI](../typer-cli.md){.internal-link target=_blank} to generate docs for your package.549550After installing it, you can use it to generate a new `README.md`:551552<div class="termy">553554```console555$ typer rick_portal_gun.main utils docs --output README.md --name rick-portal-gun556557Docs saved to: README.md558```559560</div>561562You just have to pass it the module to import (`rick_portal_gun.main`) and it will detect the `typer.Typer` app automatically.563564By specifying the `--name` of the program it will be able to use it while generating the docs.565566### Publish a new version with the docs567568Now you can publish a new version with the updated docs.569570For that you need to first increase the version in `pyproject.toml`:571572```TOML hl_lines="3"573[tool.poetry]574name = "rick-portal-gun"575version = "0.2.0"576description = ""577authors = ["Rick Sanchez <rick@example.com>"]578readme = "README.md"579580[tool.poetry.scripts]581rick-portal-gun = "rick_portal_gun.main:app"582583[tool.poetry.dependencies]584python = "^3.6"585typer = {extras = ["all"], version = "^0.1.0"}586587[tool.poetry.dev-dependencies]588pytest = "^5.2"589590[build-system]591requires = ["poetry>=0.12"]592build-backend = "poetry.masonry.api"593```594595And in the file `rick_portal_gun/__init__.py`:596597```Python598__version__ = '0.2.0'599```600601And then build and publish again:602603<div class="termy">604605```console606$ poetry publish --build607608---> 100%609610Building rick-portal-gun (0.2.0)611 - Building sdist612 - Built rick-portal-gun-0.2.0.tar.gz613614 - Building wheel615 - Built rick_portal_gun-0.2.0-py3-none-any.whl616617Publishing rick-portal-gun (0.2.0) to PyPI618 - Uploading rick-portal-gun-0.2.0.tar.gz 100%619 - Uploading rick_portal_gun-0.2.0-py3-none-any.whl 100%620```621622</div>623624And now you can go to PyPI, to the project page, and reload it, and it will now have your new generated docs.625626## What's next627628This is a very simple guide. You could add many more steps.629630For example, you should use <a href="https://git-scm.com/" class="external-link" target="_blank">Git</a>, the version control system, to save your code.631632You can add a lot of extra metadata to your `pyproject.toml`, check the docs for <a href="https://python-poetry.org/docs/libraries/" class="external-link" target="_blank">Poetry: Libraries</a>.633634You could use <a href="https://github.com/pipxproject/pipx" class="external-link" target="_blank">`pipx`</a> to manage your installed CLI Python programs in isolated environments.635636Maybe use automatic formatting with <a href="https://github.com/psf/black" class="external-link" target="_blank">Black</a>.637638You'll probably want to publish your code as open source to <a href="https://github.com/" class="external-link" target="_blank">GitHub</a>.639640And then you could integrate a <abbr title="Continuous Integration">CI</abbr> tool to run your tests and deploy your package automatically.641642And there's a long etc. But now you have the basics and you can continue on your own 🚀.
modified:docs/tutorial/using-click.md+1 added-1 removed
modified:mkdocs.yml+1 added
70 unmodified lines
71 - CLI Application Directory: 'tutorial/app-dir.md'72 - Launching Applications: 'tutorial/launch.md'73 - Testing: 'tutorial/testing.md'74 - Using Click: 'tutorial/using-click.md'75 - Building a Package: 'tutorial/package.md'76 - Typer CLI - completion for small scripts: 'typer-cli.md'77 - Alternatives, Inspiration and Comparisons: 'alternatives.md'78 - Help Typer - Get Help: 'help-typer.md'79 - Development - Contributing: 'contributing.md'
41 unmodified lines