: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
Provenance
- Commit
0830c02- Tree
99fa46b- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
150baa2
3 files changed+644 added−1 removed
added:docs/tutorial/package.md+642 added
1+When you create a CLI program with **Typer** you probably want to create your own Python package.2+3+That's what allows your users to install it and have it as an independent program that they can use in their terminal.4+5+And 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}).6+7+Nowadays, there are several ways and tools to create Python packages (what you install with `pip install something`).8+9+You might even have your favorite already.10+11+Here's a very opinionated, short guide, showing one of the alternative ways of creating a Python package with a **Typer** app, from scratch.12+13+!!! tip14+ If you already have a favorite way of creating Python packages, feel free to skip this.15+16+## Prerequisites17+18+For this guide we'll use <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a>.19+20+Poetry's docs are great, so go ahead, check them and install it.21+22+## Create a project23+24+Let's say we want to create a CLI application called `portal-gun`.25+26+To make sure your package doesn't collide with the package created by someone else, we'll name it with a prefix of your name.27+28+So, if your name is Rick, we'll call it `rick-portal-gun`.29+30+Create a project with Poetry:31+32+<div class="termy">33+34+```console35+$ poetry new rick-portal-gun36+37+Created package rick_portal_gun in rick-portal-gun38+39+// Enter the new project directory40+cd ./rick-portal-gun41+```42+43+</div>44+45+## Dependencies and environment46+47+Add `typer[all]` to your dependencies:48+49+<div class="termy">50+51+```console52+$ poetry add typer[all]53+54+// It creates a virtual environment for your project55+Creating virtualenv rick-portal-gun-w31dJa0b-py3.6 in /home/rick/.cache/pypoetry/virtualenvs56+Using version ^0.1.0 for typer57+58+Updating dependencies59+Resolving dependencies... (1.2s)60+61+Writing lock file62+63+---> 100%64+65+Package operations: 15 installs, 0 updates, 0 removals66+67+ - 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)82+83+// Activate that new virtual environment84+$ poetry shell85+86+Spawning shell within /home/rick/.cache/pypoetry/virtualenvs/rick-portal-gun-w31dJa0b-py3.687+88+// Open an editor using this new environment, for example VS Code89+$ code ./90+```91+92+</div>93+94+You can see that you have a generated project structure that looks like:95+96+```97+.98+├── poetry.lock99+├── pyproject.toml100+├── README.rst101+├── rick_portal_gun102+│ └── __init__.py103+└── tests104+ ├── __init__.py105+ └── test_rick_portal_gun.py106+```107+108+## Create your app109+110+Now let's create an extremely simple **Typer** app.111+112+Create a file `rick_portal_gun/main.py` with:113+114+```Python115+import typer116+117+118+app = typer.Typer()119+120+121+@app.callback()122+def callback():123+ """124+ Awesome Portal Gun125+ """126+127+128+@app.command()129+def shoot():130+ """131+ Shoot the portal gun132+ """133+ typer.echo("Shooting portal gun")134+135+136+@app.command()137+def load():138+ """139+ Load the portal gun140+ """141+ typer.echo("Loading portal gun")142+```143+144+!!! tip145+ As we are creating an installable Python package, there's no need to add a section with `if __name__ == "__main__:`.146+147+## Modify the README148+149+Let's change the README. By default it's a file `README.rst`.150+151+Let's change it to `README.md`. So, change the extension from `.rst` to `.md`.152+153+So that we can use Markdown instead of reStructuredText.154+155+And change the file to have something like:156+157+```Markdown158+# Portal Gun159+160+The awesome Portal Gun161+```162+163+## Modify your project metadata164+165+Edit your file `pyproject.toml`.166+167+It would look something like:168+169+```TOML170+[tool.poetry]171+name = "rick-portal-gun"172+version = "0.1.0"173+description = ""174+authors = ["Rick Sanchez <rick@example.com>"]175+176+[tool.poetry.dependencies]177+python = "^3.6"178+typer = {extras = ["all"], version = "^0.1.0"}179+180+[tool.poetry.dev-dependencies]181+pytest = "^5.2"182+183+[build-system]184+requires = ["poetry>=0.12"]185+build-backend = "poetry.masonry.api"186+```187+188+We changed the default README, so let's make it use the new `README.md`.189+190+Add the line:191+192+```TOML hl_lines="6"193+[tool.poetry]194+name = "rick-portal-gun"195+version = "0.1.0"196+description = ""197+authors = ["Rick Sanchez <rick@example.com>"]198+readme = "README.md"199+200+[tool.poetry.dependencies]201+python = "^3.6"202+typer = {extras = ["all"], version = "^0.1.0"}203+204+[tool.poetry.dev-dependencies]205+pytest = "^5.2"206+207+[build-system]208+requires = ["poetry>=0.12"]209+build-backend = "poetry.masonry.api"210+```211+212+## Add a "script"213+214+We are creating a Python package that can be installed with `pip install`.215+216+But we want it to provide a CLI program that can be executed in the shell.217+218+To do that, we add a configuration to the `pyproject.toml` in the section `[tool.poetry.scripts]`:219+220+```TOML hl_lines="8 9"221+[tool.poetry]222+name = "rick-portal-gun"223+version = "0.1.0"224+description = ""225+authors = ["Rick Sanchez <rick@example.com>"]226+readme = "README.md"227+228+[tool.poetry.scripts]229+rick-portal-gun = "rick_portal_gun.main:app"230+231+[tool.poetry.dependencies]232+python = "^3.6"233+typer = {extras = ["all"], version = "^0.1.0"}234+235+[tool.poetry.dev-dependencies]236+pytest = "^5.2"237+238+[build-system]239+requires = ["poetry>=0.12"]240+build-backend = "poetry.masonry.api"241+```242+243+Here's what that line means:244+245+`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:246+247+<div class="termy">248+249+```console250+$ rick-portal-gun251+252+// Something happens here ✨253+```254+255+</div>256+257+`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:258+259+```Python260+from rick_portal_gun.main import # something goes here261+```262+263+The `app` in `"rick_portal_gun.main:app"` is the thing to import from the module, and to call as a function, like:264+265+```Python266+from rick_portal_gun.main import app267+app()268+```269+270+That config section tells Poetry that when this package is installed we want it to create a command line program called `rick-portal-gun`.271+272+And that the object to call (like a function) is the one in the variable `app` inside of the module `rick_portal_gun.main`.273+274+## Install your package275+276+That's what we need to create a package.277+278+You can now install it:279+280+<div class="termy">281+282+```console283+$ poetry install284+285+Installing dependencies from lock file286+287+No dependencies to install or update288+289+ - Installing rick-portal-gun (0.1.0)290+```291+292+</div>293+294+## Try your CLI program295+296+Your package is installed in the environment created by Poetry, but you can already use it.297+298+<div class="termy">299+300+```console301+// You can use the which program to check which rick-portal-gun program is available (if any)302+$ which rick-portal-gun303+304+// You get the one from your environment305+/home/rick/.cache/pypoetry/virtualenvs/rick-portal-gun-w31dJa0b-py3.6/bin/rick-portal-gun306+307+// Try it308+$ rick-portal-gun309+310+// You get all the standard help311+Usage: rick-portal-gun [OPTIONS] COMMAND [ARGS]...312+313+ Awesome Portal Gun314+315+Options: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.318+319+ --help Show this message and exit.320+321+Commands:322+ load Load the portal gun323+ shoot Shoot the portal gun324+```325+326+</div>327+328+## Create a wheel package329+330+Python packages have a standard format called a "wheel". It's a file that ends in `.whl`.331+332+You can create a wheel with Poetry:333+334+<div class="termy">335+336+```console337+$ poetry build338+339+Building rick-portal-gun (0.1.0)340+ - Building sdist341+ - Built rick-portal-gun-0.1.0.tar.gz342+343+ - Building wheel344+ - Built rick_portal_gun-0.1.0-py3-none-any.whl345+```346+347+</div>348+349+After that, if you check in your project directory, you should now have a couple of extra files at `./dist/`:350+351+``` 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+```360+361+The `.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).362+363+## Test your wheel package364+365+Now you can open another terminal and install that package from the file for your own user with:366+367+<div class="termy">368+369+```console370+$ pip install --user /home/rock/code/rick-portal-gun/dist/rick_portal_gun-0.1.0-py3-none-any.whl371+372+---> 100%373+```374+375+</div>376+377+!!! warning378+ The `--user` is important, that ensures you install it in your user's directory and not in the global system.379+380+ 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.381+382+!!! 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 🚀384+385+Now you have your CLI program installed. And you can use it freely:386+387+<div class="termy">388+389+```console390+$ rick-portal-gun shoot391+392+// It works 🎉393+Shooting portal gun394+```395+396+</div>397+398+Having it installed globally (and not in a single environment), you can now install completion globally for it:399+400+<div class="termy">401+402+```console403+$ rick-portal-gun --install-completion404+405+zsh completion installed in /home/user/.zshrc.406+Completion will take effect once you restart the terminal.407+```408+409+</div>410+411+!!! tip412+ If you want to remove completion you can just delete the added line in that file.413+414+And after you restart the terminal you will get completion for your new CLI program:415+416+<div class="termy">417+418+```console419+$ rick-portal-gun [TAB][TAB]420+421+// You get completion for your CLI program ✨422+load -- Load the portal gun423+shoot -- Shoot the portal gun424+```425+426+</div>427+428+## Publish to PyPI (optional)429+430+You 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.431+432+So, go ahead and create an account there (it's free).433+434+### PyPI API token435+436+To do it, you first need to configure a PyPI auth token.437+438+Login to <a href="https://pypi.org/" class="external-link" target="_blank">PyPI</a>.439+440+And 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.441+442+Let's say your new API token is:443+444+```445+pypi-wubalubadubdub-deadbeef1234446+```447+448+Now configure Poetry to use this token with the command `poetry config pypi-token.pypi`:449+450+<div class="termy">451+452+```console453+$ poetry config pypi-token.pypi pypi-wubalubadubdub-deadbeef1234454+// It won't show any output, but it's already configured455+```456+457+</div>458+459+### Publish to PyPI460+461+Now you can publish your package with Poetry.462+463+You 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:464+465+<div class="termy">466+467+```console468+$ poetry publish --build469+470+# There are 2 files ready for publishing. Build anyway? (yes/no) [no] $ yes471+472+---> 100%473+474+Building rick-portal-gun (0.1.0)475+ - Building sdist476+ - Built rick-portal-gun-0.1.0.tar.gz477+478+ - Building wheel479+ - Built rick_portal_gun-0.1.0-py3-none-any.whl480+481+Publishing 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+```485+486+</div>487+488+Now 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>.489+490+You should now see your new "rick-portal-gun" package.491+492+### Install from PyPI493+494+Now to see that we can install it form PyPI, open another terminal, and uninstall the currently installed package.495+496+<div class="termy">497+498+```console499+$ pip uninstall rick-portal-gun500+501+Found existing installation: rick-portal-gun 0.1.0502+Uninstalling 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+```510+511+</div>512+513+And now install it again, but this time using just the name, so that `pip` pulls it from PyPI:514+515+<div class="termy">516+517+```console518+$ pip install --user rick-portal-gun519+520+// Notice that it says "Downloading" 🚀521+Collecting rick-portal-gun522+ Downloading rick_portal_gun-0.1.0-py3-none-any.whl (1.8 kB)523+Requirement already satisfied: typer[all]<0.0.12,>=0.0.11 in ./.local/lib/python3.6/site-packages (from rick-portal-gun) (0.0.11)524+Requirement 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)525+Requirement 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)526+Requirement 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)527+Installing collected packages: rick-portal-gun528+Successfully installed rick-portal-gun-0.1.0529+```530+531+</div>532+533+And now test the newly installed package from PyPI:534+535+<div class="termy">536+537+```console538+$ rick-portal-gun load539+540+// It works! 🎉541+Loading portal gun542+```543+544+</div>545+546+## Generate docs with **Typer CLI** (optional)547+548+You can install and use [Typer CLI](../typer-cli.md){.internal-link target=_blank} to generate docs for your package.549+550+After installing it, you can use it to generate a new `README.md`:551+552+<div class="termy">553+554+```console555+$ typer rick_portal_gun.main utils docs --output README.md --name rick-portal-gun556+557+Docs saved to: README.md558+```559+560+</div>561+562+You just have to pass it the module to import (`rick_portal_gun.main`) and it will detect the `typer.Typer` app automatically.563+564+By specifying the `--name` of the program it will be able to use it while generating the docs.565+566+### Publish a new version with the docs567+568+Now you can publish a new version with the updated docs.569+570+For that you need to first increase the version in `pyproject.toml`:571+572+```TOML hl_lines="3"573+[tool.poetry]574+name = "rick-portal-gun"575+version = "0.2.0"576+description = ""577+authors = ["Rick Sanchez <rick@example.com>"]578+readme = "README.md"579+580+[tool.poetry.scripts]581+rick-portal-gun = "rick_portal_gun.main:app"582+583+[tool.poetry.dependencies]584+python = "^3.6"585+typer = {extras = ["all"], version = "^0.1.0"}586+587+[tool.poetry.dev-dependencies]588+pytest = "^5.2"589+590+[build-system]591+requires = ["poetry>=0.12"]592+build-backend = "poetry.masonry.api"593+```594+595+And in the file `rick_portal_gun/__init__.py`:596+597+```Python598+__version__ = '0.2.0'599+```600+601+And then build and publish again:602+603+<div class="termy">604+605+```console606+$ poetry publish --build607+608+---> 100%609+610+Building rick-portal-gun (0.2.0)611+ - Building sdist612+ - Built rick-portal-gun-0.2.0.tar.gz613+614+ - Building wheel615+ - Built rick_portal_gun-0.2.0-py3-none-any.whl616+617+Publishing 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+```621+622+</div>623+624+And now you can go to PyPI, to the project page, and reload it, and it will now have your new generated docs.625+626+## What's next627+628+This is a very simple guide. You could add many more steps.629+630+For 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.631+632+You 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>.633+634+You 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.635+636+Maybe use automatic formatting with <a href="https://github.com/psf/black" class="external-link" target="_blank">Black</a>.637+638+You'll probably want to publish your code as open source to <a href="https://github.com/" class="external-link" target="_blank">GitHub</a>.639+640+And then you could integrate a <abbr title="Continuous Integration">CI</abbr> tool to run your tests and deploy your package automatically.641+642+And 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
183 unmodified linesExpand all184185186187188188189190183 unmodified linesExpand all
For example, to access the context, you can just declare a function parameter of type `typer.Context`.
!!! tip You can read more about using the context in the docs: [Commands: Using the Context](./commands/using-the-context.md){.internal-link target=_blank} You can read more about using the context in the docs: [Commands: Using the Context](commands/context.md){.internal-link target=_blank}
But if you need to use something based on Click decorators, you can always generate a Click object using the methods described above, and use it as you would normally use Click.modified:mkdocs.yml+1 added
70 unmodified lines71 - 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