📝 Add docs for virtual environments, environment variables, and update contributing (#946)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent 29d1d1f · Browse files · 9 files·+1262 added−190 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+1262 added−190 removed
- other:+1262 added−190 removed
Provenance
- Commit
73b9698- Tree
c1b960d- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
29d1d1f
9 files changed+1262 added−190 removed
modified:docs/tutorial/arguments/envvar.md+6 added
1234567891011121314172 unmodified linesExpand all# CLI Arguments with Environment Variables
You can also configure a *CLI argument* to read a value from an environment variable if it is not provided in the command line as a *CLI argument*.
/// tip
You can learn more about environment variables in the [Environment Variables](../../environment-variables.md){.internal-link target=_blank} page.
///
To do that, use the `envvar` parameter for `typer.Argument()`:
//// tab | Python 3.7+
172 unmodified linesExpand allmodified:docs/tutorial/index.md+7 added-43 removed
4 unmodified lines5 It covers everything you need to know from the **simplest scripts** to **complex CLI applications**.6 7 You could consider this a **book**, a **course**, the **official** and recommended way to learn **Typer**. 😎8 9-## Python types9+## Python Types10 11 If you need a refresher about how to use Python type hints, check the first part of <a href="https://fastapi.tiangolo.com/python-types/" class="external-link" target="_blank">FastAPI's Python types intro</a>.12 13 You can also check the <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">mypy cheat sheet</a>.16 unmodified lines30 These type hints are what give you autocomplete in your editor and several other features.31 32 **Typer** is based on these type hints.33 34-## Intro34+## About this Tutorial35 36 This tutorial shows you how to use **Typer** with all its features, step by step.37 38 Each section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific CLI needs.39 40-It is also built to work as a future reference.40+It is also built to work as a future reference so you can come back and see exactly what you need.41 42-So you can come back and see exactly what you need.42+## Run the Code43 44-## Run the code45-44 All the code blocks can be copied and used directly (they are tested Python files).45 46 To run any of the examples, copy the code to a file `main.py`, and run it:47 8 unmodified lines56 </div>57 58 It is **HIGHLY encouraged** that you write or copy the code, edit it and run it locally.59 62-Using it in your editor is what really shows you the benefits of **Typer**, seeing how little code you have to write, all the type checks, autocompletion, etc.60+Using it in your editor is what really shows you the benefits of **Typer**, seeing how little code you have to write, all the **inline errors**, **autocompletion**, etc.61 64-And running the examples is what will really help you understand what is going on.62+And running the examples is what will really help you **understand** what is going on.63 66-You can learn a lot more by running some examples and playing around with them than by reading all the docs here.67-68----69-70-## Install **Typer**71-72-The first step is to install **Typer**:73-74-<div class="termy">75-76-```console77-$ pip install typer78----> 100%79-Successfully installed typer click shellingham rich80-```81-82-</div>83-84-By default, `typer` comes with `rich` and `shellingham`.85-86-/// note87-88-If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.89-90-```bash91-pip install typer92-```93-94-...includes the same optional dependencies as:95-96-```bash97-pip install "typer-slim[standard]"98-```99-100-///64+You can learn a lot more by **running some examples** and **playing around** with them than by reading all the docs here.added:docs/tutorial/install.md+33 added
1+# Install **Typer**2+3+The first step is to install **Typer**.4+5+First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example with:6+7+<div class="termy">8+9+```console10+$ pip install typer11+---> 100%12+Successfully installed typer click shellingham rich13+```14+15+</div>16+17+By default, `typer` comes with `rich` and `shellingham`.18+19+/// note20+21+If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.22+23+```bash24+pip install typer25+```26+27+...includes the same optional dependencies as:28+29+```bash30+pip install "typer-slim[standard]"31+```32+33+///modified:docs/contributing.md+61 added-147 removed
2 unmodified lines3 First, you might want to see the basic ways to [help Typer and get help](help-typer.md){.internal-link target=_blank}.4 5 ## Developing6 7-If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.7+If you already cloned the <a href="https://github.com/fastapi/typer" class="external-link" target="_blank">typer repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.8 9-### Virtual environment with `venv`9+### Virtual Environment10 11-You can create a virtual environment in a directory using Python's `venv` module:11+Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`.12 13-<div class="termy">13+### Install Requirements Using `pip`14 15-```console16-$ python -m venv env17-```15+After activating the environment, install the required packages:16 19-</div>20-21-That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment.22-23-### Activate the environment24-25-Activate the new environment with:26-27-//// tab | Linux, macOS28-17 <div class="termy">18 19 ```console32-$ source ./env/bin/activate20+$ pip install -r requirements.txt21+22+---> 100%23 ```24 25 </div>26 37-////27+It will install all the dependencies and your local Typer in your local environment.28 39-//// tab | Windows PowerShell29+### Using your Local Typer30 41-<div class="termy">31+If you create a Python file that imports and uses Typer, and run it with the Python from your local environment, it will use your cloned local Typer source code.32 43-```console44-$ .\env\Scripts\Activate.ps145-```33+And if you update that local Typer source code when you run that Python file again, it will use the fresh version of Typer you just edited.34 47-</div>35+That way, you don't have to "install" your local version to be able to test every change.36 49-////37+/// note | "Technical Details"38 51-//// tab | Windows Bash39+This only happens when you install using this included `requirements.txt` instead of running `pip install typer` directly.40 53-Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):41+That is because inside the `requirements.txt` file, the local version of Typer is marked to be installed in "editable" mode, with the `-e` option.42 55-<div class="termy">43+///44 57-```console58-$ source ./env/Scripts/activate59-```45+### Format46 61-</div>47+There is a script that you can run that will format and clean all your code:48 63-////64-65-To check it worked, use:66-67-//// tab | Linux, macOS, Windows Bash68-49 <div class="termy">50 51 ```console72-$ which pip73-74-some/directory/typer/env/bin/pip52+$ bash scripts/format.sh53 ```54 55 </div>56 79-////57+It will also auto-sort all your imports.58 81-//// tab | Windows PowerShell59+## Tests60 61+There is a script that you can run locally to test all the code and generate coverage reports in HTML:62+63 <div class="termy">64 65 ```console86-$ Get-Command pip87-88-some/directory/typer/env/bin/pip66+$ bash scripts/test-cov-html.sh67 ```68 69 </div>70 93-////71+This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.72 95-If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉73+## Docs74 97-/// tip75+First, make sure you set up your environment as described above, that will install all the requirements.76 99-Every time you install a new package with `pip` under that environment, activate the environment again.77+### Docs live78 101-This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally.79+During local development, there is a script that builds the site and checks for any changes, live-reloading:80 103-///104-105-### Flit106-107-**Typer** uses <a href="https://flit.readthedocs.io/en/latest/index.html" class="external-link" target="_blank">Flit</a> to build, package and publish the project.108-109-After activating the environment as described above, install `flit`:110-81 <div class="termy">82 83 ```console114-$ pip install flit84+$ python ./scripts/docs.py live85 116----> 100%86+<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:800887+<span style="color: green;">[INFO]</span> Start watching changes88+<span style="color: green;">[INFO]</span> Start detecting changes89 ```90 91 </div>92 121-Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one).93+It will serve the documentation on `http://127.0.0.1:8008`.94 123-And now use `flit` to install the development dependencies:95+That way, you can edit the documentation/source files and see the changes live.96 125-//// tab | Linux, macOS97+/// tip98 127-<div class="termy">99+Alternatively, you can perform the same steps that scripts does manually.100 129-```console130-$ flit install --deps develop --symlink101+Go into the docs director at `docs/`:102 132----> 100%103+```console104+$ cd docs/105 ```106 135-</div>107+Then run `mkdocs` in that directory:108 137-////138-139-//// tab | Windows140-141-If you are on Windows, use `--pth-file` instead of `--symlink`:142-143-<div class="termy">144-109 ```console146-$ flit install --deps develop --pth-file147-148----> 100%110+$ mkdocs serve --dev-addr 8008111 ```112 151-</div>113+///114 153-////115+#### Typer CLI (optional)116 155-It will install all the dependencies and your local Typer in your local environment.117+The instructions here show you how to use the script at `./scripts/docs.py` with the `python` program directly.118 157-#### Using your local Typer119+But you can also use <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a>, and you will get autocompletion in your terminal for the commands after installing completion.120 159-If you create a Python file that imports and uses Typer, and run it with the Python from your local environment, it will use your local Typer source code.121+If you install Typer CLI, you can install completion with:122 161-And if you update that local Typer source code, as it is installed with `--symlink` (or `--pth-file` on Windows), when you run that Python file again, it will use the fresh version of Typer you just edited.162-163-That way, you don't have to "install" your local version to be able to test every change.164-165-### Format166-167-There is a script that you can run that will format and clean all your code:168-123 <div class="termy">124 125 ```console172-$ bash scripts/format.sh126+$ typer --install-completion127+128+zsh completion installed in /home/user/.bashrc.129+Completion will take effect once you restart the terminal.130 ```131 132 </div>133 177-It will also auto-sort all your imports.134+### Docs Structure135 179-For it to sort them correctly, you need to have Typer installed locally in your environment, with the command in the section above using `--symlink` (or `--pth-file` on Windows).136+The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.137 181-### Format imports138+And there are extra tools/scripts in place in `./scripts/docs.py`.139 183-There is another script that formats all the imports and makes sure you don't have unused imports:140+/// tip141 185-<div class="termy">142+You don't need to see the code in `./scripts/docs.py`, you just use it in the command line.143 187-```console188-$ bash scripts/format-imports.sh189-```144+///145 191-</div>192-193-As it runs one command after the other and modifies and reverts many files, it takes a bit longer to run, so it might be easier to use `scripts/format.sh` frequently and `scripts/format-imports.sh` only before committing.194-195-## Docs196-197-The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.198-146 All the documentation is in Markdown format in the directory `./docs`.147 148 Many of the tutorials have blocks of code.149 2 unmodified lines152 In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory.153 154 And those Python files are included/injected in the documentation when generating the site.155 209-### Docs for tests156+### Docs for Tests157 158 Most of the tests actually run against the example source files in the documentation.159 213-This helps making sure that:160+This helps to make sure that:161 215-* The documentation is up to date.162+* The documentation is up-to-date.163 * The documentation examples can be run as is.164 * Most of the features are covered by the documentation, ensured by test coverage.218-219-During local development, there is a script that builds the site and checks for any changes, live-reloading:220-221-<div class="termy">222-223-```console224-$ bash scripts/docs-live.sh225-226-<span style="color: green;">[INFO]</span> - Building documentation...227-<span style="color: green;">[INFO]</span> - Cleaning site directory228-<span style="color: green;">[INFO]</span> - Documentation built in 2.74 seconds229-<span style="color: green;">[INFO]</span> - Serving on http://127.0.0.1:8008230-```231-232-</div>233-234-It will serve the documentation on `http://127.0.0.1:8008`.235-236-That way, you can edit the documentation/source files and see the changes live.237-238-## Tests239-240-There is a script that you can run locally to test all the code and generate coverage reports in HTML:241-242-<div class="termy">243-244-```console245-$ bash scripts/test-cov-html.sh246-```247-248-</div>249-250-This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.added:docs/environment-variables.md+304 added
1+# Environment Variables2+3+Before we jump into **Typer** code, let's cover a bit some of the **basics** that we'll need to understand how to work with Python (and programming) in general. Let's check a bit about **environment variables**.4+5+/// tip6+7+If you already know what "environment variables" are and how to use them, feel free to skip this.8+9+///10+11+An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well).12+13+Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.14+15+## Create and Use Env Vars16+17+You can **create** and use environment variables in the **shell (terminal)**, without needing Python:18+19+//// tab | Linux, macOS, Windows Bash20+21+<div class="termy">22+23+```console24+// You could create an env var MY_NAME with25+$ export MY_NAME="Wade Wilson"26+27+// Then you could use it with other programs, like28+$ echo "Hello $MY_NAME"29+30+Hello Wade Wilson31+```32+33+</div>34+35+////36+37+//// tab | Windows PowerShell38+39+<div class="termy">40+41+```console42+// Create an env var MY_NAME43+$ $Env:MY_NAME = "Wade Wilson"44+45+// Use it with other programs, like46+$ echo "Hello $Env:MY_NAME"47+48+Hello Wade Wilson49+```50+51+</div>52+53+////54+55+## Read env vars in Python56+57+You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.58+59+For example you could have a file `main.py` with:60+61+```Python hl_lines="3"62+import os63+64+name = os.getenv("MY_NAME", "World")65+print(f"Hello {name} from Python")66+```67+68+/// tip69+70+The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.71+72+If not provided, it's `None` by default, here we provide `"World"` as the default value to use.73+74+///75+76+Then you could call that Python program:77+78+//// tab | Linux, macOS, Windows Bash79+80+<div class="termy">81+82+```console83+// Here we don't set the env var yet84+$ python main.py85+86+// As we didn't set the env var, we get the default value87+88+Hello World from Python89+90+// But if we create an environment variable first91+$ export MY_NAME="Wade Wilson"92+93+// And then call the program again94+$ python main.py95+96+// Now it can read the environment variable97+98+Hello Wade Wilson from Python99+```100+101+</div>102+103+////104+105+//// tab | Windows PowerShell106+107+<div class="termy">108+109+```console110+// Here we don't set the env var yet111+$ python main.py112+113+// As we didn't set the env var, we get the default value114+115+Hello World from Python116+117+// But if we create an environment variable first118+$ $Env:MY_NAME = "Wade Wilson"119+120+// And then call the program again121+$ python main.py122+123+// Now it can read the environment variable124+125+Hello Wade Wilson from Python126+```127+128+</div>129+130+////131+132+As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**.133+134+You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration.135+136+To do that, create it right before the program itself, on the same line:137+138+<div class="termy">139+140+```console141+// Create an env var MY_NAME in line for this program call142+$ MY_NAME="Wade Wilson" python main.py143+144+// Now it can read the environment variable145+146+Hello Wade Wilson from Python147+148+// The env var no longer exists afterwards149+$ python main.py150+151+Hello World from Python152+```153+154+</div>155+156+/// tip157+158+You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.159+160+///161+162+## Types and Validation163+164+These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).165+166+That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code.167+168+You will learn more about using environment variables for your <abbr title="command line interface">CLI</abbr> applications later in the section about [CLI Arguments with Environment Variables](./tutorial/arguments/envvar.md){.internal-link target=_blank}.169+170+## `PATH` Environment Variable171+172+There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.173+174+The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows.175+176+For example, the `PATH` environment variable could look like this:177+178+//// tab | Linux, macOS179+180+```plaintext181+/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin182+```183+184+This means that the system should look for programs in the directories:185+186+* `/usr/local/bin`187+* `/usr/bin`188+* `/bin`189+* `/usr/sbin`190+* `/sbin`191+192+////193+194+//// tab | Windows195+196+```plaintext197+C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32198+```199+200+This means that the system should look for programs in the directories:201+202+* `C:\Program Files\Python312\Scripts`203+* `C:\Program Files\Python312`204+* `C:\Windows\System32`205+206+////207+208+When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable.209+210+For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.211+212+If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.213+214+### Installing Python and Updating the `PATH`215+216+When you install Python, you might be asked if you want to update the `PATH` environment variable.217+218+//// tab | Linux, macOS219+220+Let's say you install Python and it ends up in a directory `/opt/custompython/bin`.221+222+If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.223+224+It could look like this:225+226+```plaintext227+/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin228+```229+230+This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.231+232+////233+234+//// tab | Windows235+236+Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`.237+238+If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable.239+240+```plaintext241+C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin242+```243+244+This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one.245+246+////247+248+This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.249+250+So, if you type:251+252+<div class="termy">253+254+```console255+$ python256+```257+258+</div>259+260+//// tab | Linux, macOS261+262+The system will **find** the `python` program in `/opt/custompython/bin` and run it.263+264+It would be roughly equivalent to typing:265+266+<div class="termy">267+268+```console269+$ /opt/custompython/bin/python270+```271+272+</div>273+274+////275+276+//// tab | Windows277+278+The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it.279+280+It would be roughly equivalent to typing:281+282+<div class="termy">283+284+```console285+$ C:\opt\custompython\bin\python286+```287+288+</div>289+290+////291+292+This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}.293+294+It will also be useful when you **create your own CLI programs** as, for them to be available for your users, they will need to be somewhere in the `PATH` environment variable.295+296+## Conclusion297+298+With this you should have a basic understanding of what **environment variables** are and how to use them in Python.299+300+You can also read more about them in the <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>.301+302+In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them.303+304+For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).modified:docs/index.md+2 added
50 unmodified lines51 **Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.52 53 ## Installation54 55+Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:56+57 <div class="termy">58 59 ```console60 $ pip install typer330 unmodified linesadded:docs/virtual-environments.md+844 added
1+# Virtual Environments2+3+When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project.4+5+/// info6+7+If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓8+9+///10+11+/// tip12+13+A **virtual environment** is different than an **environment variable**.14+15+An **environment variable** is a variable in the system that can be used by programs.16+17+A **virtual environment** is a directory with some files in it.18+19+///20+21+/// info22+23+This page will teach you how to use **virtual environments** and how they work.24+25+If you are ready to adopt a **tool that manages everything** for you (including installing Python), try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>.26+27+///28+29+## Create a Project30+31+First, create a directory for your project.32+33+What I normally do is that I create a directory named `code` inside my home/user directory.34+35+And inside of that I create one directory per project.36+37+<div class="termy">38+39+```console40+// Go to the home directory41+$ cd42+// Create a directory for all your code projects43+$ mkdir code44+// Enter into that code directory45+$ cd code46+// Create a directory for this project47+$ mkdir awesome-project48+// Enter into that project directory49+$ cd awesome-project50+```51+52+</div>53+54+## Create a Virtual Environment55+56+When you start working on a Python project **for the first time**, create a virtual environment **<abbr title="there are other options, this is a simple guideline">inside your project</abbr>**.57+58+/// tip59+60+You only need to do this **once per project**, not every time you work.61+62+///63+64+//// tab | `venv`65+66+To create a virtual environment, you can use the `venv` module that comes with Python.67+68+<div class="termy">69+70+```console71+$ python -m venv .venv72+```73+74+</div>75+76+/// details | What that command means77+78+* `python`: use the program called `python`79+* `-m`: call a module as a script, we'll tell it which module next80+* `venv`: use the module called `venv` that normally comes installed with Python81+* `.venv`: create the virtual environment in the new directory `.venv`82+83+///84+85+////86+87+//// tab | `uv`88+89+If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> installed, you can use it to create a virtual environment.90+91+<div class="termy">92+93+```console94+$ uv venv95+```96+97+</div>98+99+/// tip100+101+By default, `uv` will create a virtual environment in a directory called `.venv`.102+103+But you could customize it passing an additional argument with the directory name.104+105+///106+107+////108+109+That command creates a new virtual environment in a directory called `.venv`.110+111+/// details | `.venv` or other name112+113+You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`.114+115+///116+117+## Activate the Virtual Environment118+119+Activate the new virtual environment so that any Python command you run or package you install uses it.120+121+/// tip122+123+Do this **every time** you start a **new terminal session** to work on the project.124+125+///126+127+//// tab | Linux, macOS128+129+<div class="termy">130+131+```console132+$ source .venv/bin/activate133+```134+135+</div>136+137+////138+139+//// tab | Windows PowerShell140+141+<div class="termy">142+143+```console144+$ .venv\Scripts\Activate.ps1145+```146+147+</div>148+149+////150+151+//// tab | Windows Bash152+153+Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):154+155+<div class="termy">156+157+```console158+$ source .venv/Scripts/activate159+```160+161+</div>162+163+////164+165+/// tip166+167+Every time you install a **new package** in that environment, **activate** the environment again.168+169+This makes sure that if you use a **terminal (<abbr title="command line interface">CLI</abbr>) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need.170+171+///172+173+## Check the Virtual Environment is Active174+175+Check that the virtual environment is active (the previous command worked).176+177+/// tip178+179+This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended.180+181+///182+183+//// tab | Linux, macOS, Windows Bash184+185+<div class="termy">186+187+```console188+$ which python189+190+/home/user/code/awesome-project/.venv/bin/python191+```192+193+</div>194+195+If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉196+197+////198+199+//// tab | Windows PowerShell200+201+<div class="termy">202+203+```console204+$ Get-Command python205+206+C:\Users\user\code\awesome-project\.venv\Scripts\python207+```208+209+</div>210+211+If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉212+213+////214+215+## Upgrade `pip`216+217+/// tip218+219+If you use <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎220+221+///222+223+If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version.224+225+Many exotic errors while installing a package are solved by just upgrading `pip` first.226+227+/// tip228+229+You would normally do this **once**, right after you create the virtual environment.230+231+///232+233+Make sure the virtual environment is active (with the command above) and then run:234+235+<div class="termy">236+237+```console238+$ python -m pip install --upgrade pip239+240+---> 100%241+```242+243+</div>244+245+## Add `.gitignore`246+247+If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git.248+249+/// tip250+251+If you used <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> to create the virtual environment, it already did this for you, you can skip this step. 😎252+253+///254+255+/// tip256+257+Do this **once**, right after you create the virtual environment.258+259+///260+261+<div class="termy">262+263+```console264+$ echo "*" > .venv/.gitignore265+```266+267+</div>268+269+/// details | What that command means270+271+* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit)272+* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>`273+* `.gitignore`: the name of the file where the text should be written274+275+And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory.276+277+That command will create a file `.gitignore` with the content:278+279+```gitignore280+*281+```282+283+///284+285+## Install Packages286+287+After activating the environment, you can install packages in it.288+289+/// tip290+291+Do this **once** when installing or upgrading the packages your project needs.292+293+If you need to upgrade a version or add a new package you would **do this again**.294+295+///296+297+### Install Packages Directly298+299+If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly.300+301+/// tip302+303+It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`).304+305+///306+307+//// tab | `pip`308+309+<div class="termy">310+311+```console312+$ pip install typer313+314+---> 100%315+```316+317+</div>318+319+////320+321+//// tab | `uv`322+323+If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:324+325+<div class="termy">326+327+```console328+$ uv pip install typer329+---> 100%330+```331+332+</div>333+334+////335+336+### Install from `requirements.txt`337+338+If you have a `requirements.txt`, you can now use it to install its packages.339+340+//// tab | `pip`341+342+<div class="termy">343+344+```console345+$ pip install -r requirements.txt346+---> 100%347+```348+349+</div>350+351+////352+353+//// tab | `uv`354+355+If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:356+357+<div class="termy">358+359+```console360+$ uv pip install -r requirements.txt361+---> 100%362+```363+364+</div>365+366+////367+368+/// details | `requirements.txt`369+370+A `requirements.txt` with some packages could look like:371+372+```requirements.txt373+typer==0.13.0374+rich==13.7.1375+```376+377+///378+379+## Run Your Program380+381+After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there.382+383+<div class="termy">384+385+```console386+$ python main.py387+388+Hello World389+```390+391+</div>392+393+## Configure Your Editor394+395+You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors.396+397+For example:398+399+* <a href="https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment" class="external-link" target="_blank">VS Code</a>400+* <a href="https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html" class="external-link" target="_blank">PyCharm</a>401+402+/// tip403+404+You normally have to do this only **once**, when you create the virtual environment.405+406+///407+408+## Deactivate the Virtual Environment409+410+Once you are done working on your project you can **deactivate** the virtual environment.411+412+<div class="termy">413+414+```console415+$ deactivate416+```417+418+</div>419+420+This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there.421+422+## Ready to Work423+424+Now you're ready to start working on your project.425+426+427+428+/// tip429+430+Do you want to understand what's all that above?431+432+Continue reading. 👇🤓433+434+///435+436+## Why Virtual Environments437+438+To work with Typer you need to install <a href="https://www.python.org/" class="external-link" target="_blank">Python</a>.439+440+After that, you would need to **install** Typer and any other **packages** you want to use.441+442+To install packages you would normally use the `pip` command that comes with Python (or similar alternatives).443+444+Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python).445+446+### The Problem447+448+So, what's the problem with installing packages in the global Python environment?449+450+At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱451+452+For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`.453+454+```mermaid455+flowchart LR456+ stone(philosophers-stone) -->|requires| harry-1[harry v1]457+```458+459+Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**.460+461+```mermaid462+flowchart LR463+ azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]464+```465+466+But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install.467+468+If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with:469+470+<div class="termy">471+472+```console473+$ pip install "harry==1"474+```475+476+</div>477+478+And then you would end up with `harry` version `1` installed in your global Python environment.479+480+```mermaid481+flowchart LR482+ subgraph global[global env]483+ harry-1[harry v1]484+ end485+ subgraph stone-project[philosophers-stone project]486+ stone(philosophers-stone) -->|requires| harry-1487+ end488+```489+490+But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`).491+492+<div class="termy">493+494+```console495+$ pip install "harry==3"496+```497+498+</div>499+500+And then you would end up with `harry` version `3` installed in your global Python environment.501+502+And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`.503+504+```mermaid505+flowchart LR506+ subgraph global[global env]507+ harry-1[<strike>harry v1</strike>]508+ style harry-1 fill:#ccc,stroke-dasharray: 5 5509+ harry-3[harry v3]510+ end511+ subgraph stone-project[philosophers-stone project]512+ stone(philosophers-stone) -.-x|⛔️| harry-1513+ end514+ subgraph azkaban-project[prisoner-of-azkaban project]515+ azkaban(prisoner-of-azkaban) --> |requires| harry-3516+ end517+```518+519+/// tip520+521+It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly.522+523+///524+525+Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working.526+527+Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system.528+529+## Where are Packages Installed530+531+When you install Python, it creates some directories with some files in your computer.532+533+Some of these directories are the ones in charge of having all the packages you install.534+535+When you run:536+537+<div class="termy">538+539+```console540+// Don't run this now, it's just an example 🤓541+$ pip install typer542+---> 100%543+```544+545+</div>546+547+That will download a compressed file with the Typer code, normally from <a href="https://pypi.org/project/typer/" class="external-link" target="_blank">PyPI</a>.548+549+It will also **download** files for other packages that Typer depends on.550+551+Then it will **extract** all those files and put them in a directory in your computer.552+553+By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.554+555+## What are Virtual Environments556+557+The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on.558+559+A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project.560+561+This way, each project will have it's own virtual environment (`.venv` directory) with its own packages.562+563+```mermaid564+flowchart TB565+ subgraph stone-project[philosophers-stone project]566+ stone(philosophers-stone) --->|requires| harry-1567+ subgraph venv1[.venv]568+ harry-1[harry v1]569+ end570+ end571+ subgraph azkaban-project[prisoner-of-azkaban project]572+ azkaban(prisoner-of-azkaban) --->|requires| harry-3573+ subgraph venv2[.venv]574+ harry-3[harry v3]575+ end576+ end577+ stone-project ~~~ azkaban-project578+```579+580+## What Does Activating a Virtual Environment Mean581+582+When you activate a virtual environment, for example with:583+584+//// tab | Linux, macOS585+586+<div class="termy">587+588+```console589+$ source .venv/bin/activate590+```591+592+</div>593+594+////595+596+//// tab | Windows PowerShell597+598+<div class="termy">599+600+```console601+$ .venv\Scripts\Activate.ps1602+```603+604+</div>605+606+////607+608+//// tab | Windows Bash609+610+Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):611+612+<div class="termy">613+614+```console615+$ source .venv/Scripts/activate616+```617+618+</div>619+620+////621+622+That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands.623+624+One of those variables is the `PATH` variable.625+626+/// tip627+628+You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section.629+630+///631+632+Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable.633+634+Let's say that before activating the environment, the `PATH` variable looked like this:635+636+//// tab | Linux, macOS637+638+```plaintext639+/usr/bin:/bin:/usr/sbin:/sbin640+```641+642+That means that the system would look for programs in:643+644+* `/usr/bin`645+* `/bin`646+* `/usr/sbin`647+* `/sbin`648+649+////650+651+//// tab | Windows652+653+```plaintext654+C:\Windows\System32655+```656+657+That means that the system would look for programs in:658+659+* `C:\Windows\System32`660+661+////662+663+After activating the virtual environment, the `PATH` variable would look something like this:664+665+//// tab | Linux, macOS666+667+```plaintext668+/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin669+```670+671+That means that the system will now start looking first look for programs in:672+673+```plaintext674+/home/user/code/awesome-project/.venv/bin675+```676+677+before looking in the other directories.678+679+So, when you type `python` in the terminal, the system will find the Python program in680+681+```plaintext682+/home/user/code/awesome-project/.venv/bin/python683+```684+685+and use that one.686+687+////688+689+//// tab | Windows690+691+```plaintext692+C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32693+```694+695+That means that the system will now start looking first look for programs in:696+697+```plaintext698+C:\Users\user\code\awesome-project\.venv\Scripts699+```700+701+before looking in the other directories.702+703+So, when you type `python` in the terminal, the system will find the Python program in704+705+```plaintext706+C:\Users\user\code\awesome-project\.venv\Scripts\python707+```708+709+and use that one.710+711+////712+713+An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment).714+715+Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does.716+717+## Checking a Virtual Environment718+719+When you check if a virtual environment is active, for example with:720+721+//// tab | Linux, macOS, Windows Bash722+723+<div class="termy">724+725+```console726+$ which python727+728+/home/user/code/awesome-project/.venv/bin/python729+```730+731+</div>732+733+////734+735+//// tab | Windows PowerShell736+737+<div class="termy">738+739+```console740+$ Get-Command python741+742+C:\Users\user\code\awesome-project\.venv\Scripts\python743+```744+745+</div>746+747+////748+749+That means that the `python` program that will be used is the one **in the virtual environment**.750+751+you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell.752+753+The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program.754+755+The most important part is that when you call `python`, that is the exact "`python`" that will be executed.756+757+So, you can confirm if you are in the correct virtual environment.758+759+/// tip760+761+It's easy to activate one virtual environment, get one Python, and then **go to another project**.762+763+And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project.764+765+It's useful being able to check what `python` is being used. 🤓766+767+///768+769+## Why Deactivate a Virtual Environment770+771+For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment.772+773+And then you want to work on **another project** `prisoner-of-azkaban`.774+775+You go to that project:776+777+<div class="termy">778+779+```console780+$ cd ~/code/prisoner-of-azkaban781+```782+783+</div>784+785+If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`.786+787+<div class="termy">788+789+```console790+$ cd ~/code/prisoner-of-azkaban791+792+$ python main.py793+794+// Error importing sirius, it's not installed 😱795+Traceback (most recent call last):796+ File "main.py", line 1, in <module>797+ import sirius798+```799+800+</div>801+802+But if you deactivate the virtual environment and activate the new one for `prisoner-of-askaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`.803+804+<div class="termy">805+806+```console807+$ cd ~/code/prisoner-of-azkaban808+809+// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎810+$ deactivate811+812+// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀813+$ source .venv/bin/activate814+815+// Now when you run python, it will find the package sirius installed in this virtual environment ✨816+$ python main.py817+818+I solemnly swear 🐺819+```820+821+</div>822+823+## Alternatives824+825+This is a simple guide to get you started and teach you how everything works **underneath**.826+827+There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.828+829+Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>.830+831+`uv` can do a lot of things, it can:832+833+* **Install Python** for you, including different versions834+* Manage the **virtual environment** for your projects835+* Install **packages**836+* Manage package **dependencies and versions** for your project837+* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking**838+* And many other things839+840+## Conclusion841+842+If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓843+844+Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎modified:mkdocs.yml+3 added
70 unmodified lines71 - Typer: index.md72 - features.md73 - Tutorial - User Guide:74 - tutorial/index.md75+ - environment-variables.md76+ - virtual-environments.md77+ - tutorial/install.md78 - tutorial/first-steps.md79 - tutorial/printing.md80 - tutorial/terminating.md81 - CLI Arguments:156 unmodified linesmodified:README.md+2 added
44 unmodified lines45 **Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.46 47 ## Installation48 49+Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:50+51 <div class="termy">52 53 ```console54 $ pip install typer330 unmodified lines