Skip to content
Myr

📝 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

9 files+1262 added−190 removed

modified:docs/tutorial/arguments/envvar.md+6 added
modified:docs/tutorial/index.md+7 added-43 removed
4 unmodified lines
5It covers everything you need to know from the **simplest scripts** to **complex CLI applications**.67You could consider this a **book**, a **course**, the **official** and recommended way to learn **Typer**. 😎89## Python types9## Python Types1011If 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>.1213You 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 lines
30These type hints are what give you autocomplete in your editor and several other features.3132**Typer** is based on these type hints.3334## Intro34## About this Tutorial3536This tutorial shows you how to use **Typer** with all its features, step by step.3738Each 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.3940It is also built to work as a future reference.40It is also built to work as a future reference so you can come back and see exactly what you need.4142So you can come back and see exactly what you need.42## Run the Code4344## Run the code4544All the code blocks can be copied and used directly (they are tested Python files).4546To run any of the examples, copy the code to a file `main.py`, and run it:47
8 unmodified lines
56</div>5758It is **HIGHLY encouraged** that you write or copy the code, edit it and run it locally.5962Using 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.60Using 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.6164And running the examples is what will really help you understand what is going on.62And running the examples is what will really help you **understand** what is going on.6366You can learn a lot more by running some examples and playing around with them than by reading all the docs here.6768---6970## Install **Typer**7172The first step is to install **Typer**:7374<div class="termy">7576```console77$ pip install typer78---> 100%79Successfully installed typer click shellingham rich80```8182</div>8384By default, `typer` comes with `rich` and `shellingham`.8586/// note8788If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.8990```bash91pip install typer92```9394...includes the same optional dependencies as:9596```bash97pip install "typer-slim[standard]"98```99100///64You 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**23The first step is to install **Typer**.45First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example with:67<div class="termy">89```console10$ pip install typer11---> 100%12Successfully installed typer click shellingham rich13```1415</div>1617By default, `typer` comes with `rich` and `shellingham`.1819/// note2021If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.2223```bash24pip install typer25```2627...includes the same optional dependencies as:2829```bash30pip install "typer-slim[standard]"31```3233///
modified:docs/contributing.md+61 added-147 removed
2 unmodified lines
3First, you might want to see the basic ways to [help Typer and get help](help-typer.md){.internal-link target=_blank}.45## Developing67If 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.7If 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.89### Virtual environment with `venv`9### Virtual Environment1011You can create a virtual environment in a directory using Python's `venv` module:11Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`.1213<div class="termy">13### Install Requirements Using `pip`1415```console16$ python -m venv env17```15After activating the environment, install the required packages:1619</div>2021That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment.2223### Activate the environment2425Activate the new environment with:2627//// tab | Linux, macOS2817<div class="termy">1819```console32$ source ./env/bin/activate20$ pip install -r requirements.txt2122---> 100%23```2425</div>2637////27It will install all the dependencies and your local Typer in your local environment.2839//// tab | Windows PowerShell29### Using your Local Typer3041<div class="termy">31If 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.3243```console44$ .\env\Scripts\Activate.ps145```33And 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.3447</div>35That way, you don't have to "install" your local version to be able to test every change.3649////37/// note | "Technical Details"3851//// tab | Windows Bash39This only happens when you install using this included `requirements.txt` instead of running `pip install typer` directly.4053Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):41That is because inside the `requirements.txt` file, the local version of Typer is marked to be installed in "editable" mode, with the `-e` option.4255<div class="termy">43///4457```console58$ source ./env/Scripts/activate59```45### Format4661</div>47There is a script that you can run that will format and clean all your code:4863////6465To check it worked, use:6667//// tab | Linux, macOS, Windows Bash6849<div class="termy">5051```console72$ which pip7374some/directory/typer/env/bin/pip52$ bash scripts/format.sh53```5455</div>5679////57It will also auto-sort all your imports.5881//// tab | Windows PowerShell59## Tests6061There is a script that you can run locally to test all the code and generate coverage reports in HTML:6263<div class="termy">6465```console86$ Get-Command pip8788some/directory/typer/env/bin/pip66$ bash scripts/test-cov-html.sh67```6869</div>7093////71This 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.7295If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉73## Docs7497/// tip75First, make sure you set up your environment as described above, that will install all the requirements.7699Every time you install a new package with `pip` under that environment, activate the environment again.77### Docs live78101This 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.79During local development, there is a script that builds the site and checks for any changes, live-reloading:80103///104105### Flit106107**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.108109After activating the environment as described above, install `flit`:11081<div class="termy">8283```console114$ pip install flit84$ python ./scripts/docs.py live85116---> 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```9091</div>92121Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one).93It will serve the documentation on `http://127.0.0.1:8008`.94123And now use `flit` to install the development dependencies:95That way, you can edit the documentation/source files and see the changes live.96125//// tab | Linux, macOS97/// tip98127<div class="termy">99Alternatively, you can perform the same steps that scripts does manually.100129```console130$ flit install --deps develop --symlink101Go into the docs director at `docs/`:102132---> 100%103```console104$ cd docs/105```106135</div>107Then run `mkdocs` in that directory:108137////138139//// tab | Windows140141If you are on Windows, use `--pth-file` instead of `--symlink`:142143<div class="termy">144109```console146$ flit install --deps develop --pth-file147148---> 100%110$ mkdocs serve --dev-addr 8008111```112151</div>113///114153////115#### Typer CLI (optional)116155It will install all the dependencies and your local Typer in your local environment.117The instructions here show you how to use the script at `./scripts/docs.py` with the `python` program directly.118157#### Using your local Typer119But 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.120159If 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.121If you install Typer CLI, you can install completion with:122161And 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.162163That way, you don't have to "install" your local version to be able to test every change.164165### Format166167There is a script that you can run that will format and clean all your code:168123<div class="termy">124125```console172$ bash scripts/format.sh126$ typer --install-completion127128zsh completion installed in /home/user/.bashrc.129Completion will take effect once you restart the terminal.130```131132</div>133177It will also auto-sort all your imports.134### Docs Structure135179For 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).136The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.137181### Format imports138And there are extra tools/scripts in place in `./scripts/docs.py`.139183There is another script that formats all the imports and makes sure you don't have unused imports:140/// tip141185<div class="termy">142You don't need to see the code in `./scripts/docs.py`, you just use it in the command line.143187```console188$ bash scripts/format-imports.sh189```144///145191</div>192193As 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.194195## Docs196197The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.198146All the documentation is in Markdown format in the directory `./docs`.147148Many of the tutorials have blocks of code.149
2 unmodified lines
152In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory.153154And those Python files are included/injected in the documentation when generating the site.155209### Docs for tests156### Docs for Tests157158Most of the tests actually run against the example source files in the documentation.159213This helps making sure that:160This helps to make sure that:161215* 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.218219During local development, there is a script that builds the site and checks for any changes, live-reloading:220221<div class="termy">222223```console224$ bash scripts/docs-live.sh225226<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```231232</div>233234It will serve the documentation on `http://127.0.0.1:8008`.235236That way, you can edit the documentation/source files and see the changes live.237238## Tests239240There is a script that you can run locally to test all the code and generate coverage reports in HTML:241242<div class="termy">243244```console245$ bash scripts/test-cov-html.sh246```247248</div>249250This 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 Variables23Before 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**.45/// tip67If you already know what "environment variables" are and how to use them, feel free to skip this.89///1011An 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).1213Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.1415## Create and Use Env Vars1617You can **create** and use environment variables in the **shell (terminal)**, without needing Python:1819//// tab | Linux, macOS, Windows Bash2021<div class="termy">2223```console24// You could create an env var MY_NAME with25$ export MY_NAME="Wade Wilson"2627// Then you could use it with other programs, like28$ echo "Hello $MY_NAME"2930Hello Wade Wilson31```3233</div>3435////3637//// tab | Windows PowerShell3839<div class="termy">4041```console42// Create an env var MY_NAME43$ $Env:MY_NAME = "Wade Wilson"4445// Use it with other programs, like46$ echo "Hello $Env:MY_NAME"4748Hello Wade Wilson49```5051</div>5253////5455## Read env vars in Python5657You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.5859For example you could have a file `main.py` with:6061```Python hl_lines="3"62import os6364name = os.getenv("MY_NAME", "World")65print(f"Hello {name} from Python")66```6768/// tip6970The 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.7172If not provided, it's `None` by default, here we provide `"World"` as the default value to use.7374///7576Then you could call that Python program:7778//// tab | Linux, macOS, Windows Bash7980<div class="termy">8182```console83// Here we don't set the env var yet84$ python main.py8586// As we didn't set the env var, we get the default value8788Hello World from Python8990// But if we create an environment variable first91$ export MY_NAME="Wade Wilson"9293// And then call the program again94$ python main.py9596// Now it can read the environment variable9798Hello Wade Wilson from Python99```100101</div>102103////104105//// tab | Windows PowerShell106107<div class="termy">108109```console110// Here we don't set the env var yet111$ python main.py112113// As we didn't set the env var, we get the default value114115Hello World from Python116117// But if we create an environment variable first118$ $Env:MY_NAME = "Wade Wilson"119120// And then call the program again121$ python main.py122123// Now it can read the environment variable124125Hello Wade Wilson from Python126```127128</div>129130////131132As 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**.133134You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration.135136To do that, create it right before the program itself, on the same line:137138<div class="termy">139140```console141// Create an env var MY_NAME in line for this program call142$ MY_NAME="Wade Wilson" python main.py143144// Now it can read the environment variable145146Hello Wade Wilson from Python147148// The env var no longer exists afterwards149$ python main.py150151Hello World from Python152```153154</div>155156/// tip157158You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.159160///161162## Types and Validation163164These 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).165166That 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.167168You 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}.169170## `PATH` Environment Variable171172There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.173174The 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.175176For example, the `PATH` environment variable could look like this:177178//// tab | Linux, macOS179180```plaintext181/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin182```183184This means that the system should look for programs in the directories:185186* `/usr/local/bin`187* `/usr/bin`188* `/bin`189* `/usr/sbin`190* `/sbin`191192////193194//// tab | Windows195196```plaintext197C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32198```199200This means that the system should look for programs in the directories:201202* `C:\Program Files\Python312\Scripts`203* `C:\Program Files\Python312`204* `C:\Windows\System32`205206////207208When 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.209210For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.211212If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.213214### Installing Python and Updating the `PATH`215216When you install Python, you might be asked if you want to update the `PATH` environment variable.217218//// tab | Linux, macOS219220Let's say you install Python and it ends up in a directory `/opt/custompython/bin`.221222If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.223224It could look like this:225226```plaintext227/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin228```229230This 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.231232////233234//// tab | Windows235236Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`.237238If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable.239240```plaintext241C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin242```243244This 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.245246////247248This 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.249250So, if you type:251252<div class="termy">253254```console255$ python256```257258</div>259260//// tab | Linux, macOS261262The system will **find** the `python` program in `/opt/custompython/bin` and run it.263264It would be roughly equivalent to typing:265266<div class="termy">267268```console269$ /opt/custompython/bin/python270```271272</div>273274////275276//// tab | Windows277278The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it.279280It would be roughly equivalent to typing:281282<div class="termy">283284```console285$ C:\opt\custompython\bin\python286```287288</div>289290////291292This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}.293294It 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.295296## Conclusion297298With this you should have a basic understanding of what **environment variables** are and how to use them in Python.299300You 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>.301302In 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.303304For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).
modified:docs/index.md+2 added
50 unmodified lines
51**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.5253## Installation5455Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:5657<div class="termy">5859```console60$ pip install typer
330 unmodified lines
added:docs/virtual-environments.md+844 added
1# Virtual Environments23When 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.45/// info67If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓89///1011/// tip1213A **virtual environment** is different than an **environment variable**.1415An **environment variable** is a variable in the system that can be used by programs.1617A **virtual environment** is a directory with some files in it.1819///2021/// info2223This page will teach you how to use **virtual environments** and how they work.2425If 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>.2627///2829## Create a Project3031First, create a directory for your project.3233What I normally do is that I create a directory named `code` inside my home/user directory.3435And inside of that I create one directory per project.3637<div class="termy">3839```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```5152</div>5354## Create a Virtual Environment5556When 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>**.5758/// tip5960You only need to do this **once per project**, not every time you work.6162///6364//// tab | `venv`6566To create a virtual environment, you can use the `venv` module that comes with Python.6768<div class="termy">6970```console71$ python -m venv .venv72```7374</div>7576/// details | What that command means7778* `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`8283///8485////8687//// tab | `uv`8889If 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.9091<div class="termy">9293```console94$ uv venv95```9697</div>9899/// tip100101By default, `uv` will create a virtual environment in a directory called `.venv`.102103But you could customize it passing an additional argument with the directory name.104105///106107////108109That command creates a new virtual environment in a directory called `.venv`.110111/// details | `.venv` or other name112113You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`.114115///116117## Activate the Virtual Environment118119Activate the new virtual environment so that any Python command you run or package you install uses it.120121/// tip122123Do this **every time** you start a **new terminal session** to work on the project.124125///126127//// tab | Linux, macOS128129<div class="termy">130131```console132$ source .venv/bin/activate133```134135</div>136137////138139//// tab | Windows PowerShell140141<div class="termy">142143```console144$ .venv\Scripts\Activate.ps1145```146147</div>148149////150151//// tab | Windows Bash152153Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):154155<div class="termy">156157```console158$ source .venv/Scripts/activate159```160161</div>162163////164165/// tip166167Every time you install a **new package** in that environment, **activate** the environment again.168169This 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.170171///172173## Check the Virtual Environment is Active174175Check that the virtual environment is active (the previous command worked).176177/// tip178179This 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.180181///182183//// tab | Linux, macOS, Windows Bash184185<div class="termy">186187```console188$ which python189190/home/user/code/awesome-project/.venv/bin/python191```192193</div>194195If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉196197////198199//// tab | Windows PowerShell200201<div class="termy">202203```console204$ Get-Command python205206C:\Users\user\code\awesome-project\.venv\Scripts\python207```208209</div>210211If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉212213////214215## Upgrade `pip`216217/// tip218219If 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`. 😎220221///222223If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version.224225Many exotic errors while installing a package are solved by just upgrading `pip` first.226227/// tip228229You would normally do this **once**, right after you create the virtual environment.230231///232233Make sure the virtual environment is active (with the command above) and then run:234235<div class="termy">236237```console238$ python -m pip install --upgrade pip239240---> 100%241```242243</div>244245## Add `.gitignore`246247If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git.248249/// tip250251If 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. 😎252253///254255/// tip256257Do this **once**, right after you create the virtual environment.258259///260261<div class="termy">262263```console264$ echo "*" > .venv/.gitignore265```266267</div>268269/// details | What that command means270271* `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 written274275And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory.276277That command will create a file `.gitignore` with the content:278279```gitignore280*281```282283///284285## Install Packages286287After activating the environment, you can install packages in it.288289/// tip290291Do this **once** when installing or upgrading the packages your project needs.292293If you need to upgrade a version or add a new package you would **do this again**.294295///296297### Install Packages Directly298299If 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.300301/// tip302303It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`).304305///306307//// tab | `pip`308309<div class="termy">310311```console312$ pip install typer313314---> 100%315```316317</div>318319////320321//// tab | `uv`322323If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:324325<div class="termy">326327```console328$ uv pip install typer329---> 100%330```331332</div>333334////335336### Install from `requirements.txt`337338If you have a `requirements.txt`, you can now use it to install its packages.339340//// tab | `pip`341342<div class="termy">343344```console345$ pip install -r requirements.txt346---> 100%347```348349</div>350351////352353//// tab | `uv`354355If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:356357<div class="termy">358359```console360$ uv pip install -r requirements.txt361---> 100%362```363364</div>365366////367368/// details | `requirements.txt`369370A `requirements.txt` with some packages could look like:371372```requirements.txt373typer==0.13.0374rich==13.7.1375```376377///378379## Run Your Program380381After 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.382383<div class="termy">384385```console386$ python main.py387388Hello World389```390391</div>392393## Configure Your Editor394395You 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.396397For example:398399* <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>401402/// tip403404You normally have to do this only **once**, when you create the virtual environment.405406///407408## Deactivate the Virtual Environment409410Once you are done working on your project you can **deactivate** the virtual environment.411412<div class="termy">413414```console415$ deactivate416```417418</div>419420This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there.421422## Ready to Work423424Now you're ready to start working on your project.425426427428/// tip429430Do you want to understand what's all that above?431432Continue reading. 👇🤓433434///435436## Why Virtual Environments437438To work with Typer you need to install <a href="https://www.python.org/" class="external-link" target="_blank">Python</a>.439440After that, you would need to **install** Typer and any other **packages** you want to use.441442To install packages you would normally use the `pip` command that comes with Python (or similar alternatives).443444Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python).445446### The Problem447448So, what's the problem with installing packages in the global Python environment?449450At 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. 😱451452For 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`.453454```mermaid455flowchart LR456 stone(philosophers-stone) -->|requires| harry-1[harry v1]457```458459Then, 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`**.460461```mermaid462flowchart LR463 azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]464```465466But 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.467468If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with:469470<div class="termy">471472```console473$ pip install "harry==1"474```475476</div>477478And then you would end up with `harry` version `1` installed in your global Python environment.479480```mermaid481flowchart 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```489490But 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`).491492<div class="termy">493494```console495$ pip install "harry==3"496```497498</div>499500And then you would end up with `harry` version `3` installed in your global Python environment.501502And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`.503504```mermaid505flowchart 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```518519/// tip520521It'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.522523///524525Now, 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.526527Also, 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.528529## Where are Packages Installed530531When you install Python, it creates some directories with some files in your computer.532533Some of these directories are the ones in charge of having all the packages you install.534535When you run:536537<div class="termy">538539```console540// Don't run this now, it's just an example 🤓541$ pip install typer542---> 100%543```544545</div>546547That 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>.548549It will also **download** files for other packages that Typer depends on.550551Then it will **extract** all those files and put them in a directory in your computer.552553By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.554555## What are Virtual Environments556557The 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.558559A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project.560561This way, each project will have it's own virtual environment (`.venv` directory) with its own packages.562563```mermaid564flowchart 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```579580## What Does Activating a Virtual Environment Mean581582When you activate a virtual environment, for example with:583584//// tab | Linux, macOS585586<div class="termy">587588```console589$ source .venv/bin/activate590```591592</div>593594////595596//// tab | Windows PowerShell597598<div class="termy">599600```console601$ .venv\Scripts\Activate.ps1602```603604</div>605606////607608//// tab | Windows Bash609610Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):611612<div class="termy">613614```console615$ source .venv/Scripts/activate616```617618</div>619620////621622That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands.623624One of those variables is the `PATH` variable.625626/// tip627628You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section.629630///631632Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable.633634Let's say that before activating the environment, the `PATH` variable looked like this:635636//// tab | Linux, macOS637638```plaintext639/usr/bin:/bin:/usr/sbin:/sbin640```641642That means that the system would look for programs in:643644* `/usr/bin`645* `/bin`646* `/usr/sbin`647* `/sbin`648649////650651//// tab | Windows652653```plaintext654C:\Windows\System32655```656657That means that the system would look for programs in:658659* `C:\Windows\System32`660661////662663After activating the virtual environment, the `PATH` variable would look something like this:664665//// tab | Linux, macOS666667```plaintext668/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin669```670671That means that the system will now start looking first look for programs in:672673```plaintext674/home/user/code/awesome-project/.venv/bin675```676677before looking in the other directories.678679So, when you type `python` in the terminal, the system will find the Python program in680681```plaintext682/home/user/code/awesome-project/.venv/bin/python683```684685and use that one.686687////688689//// tab | Windows690691```plaintext692C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32693```694695That means that the system will now start looking first look for programs in:696697```plaintext698C:\Users\user\code\awesome-project\.venv\Scripts699```700701before looking in the other directories.702703So, when you type `python` in the terminal, the system will find the Python program in704705```plaintext706C:\Users\user\code\awesome-project\.venv\Scripts\python707```708709and use that one.710711////712713An 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).714715Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does.716717## Checking a Virtual Environment718719When you check if a virtual environment is active, for example with:720721//// tab | Linux, macOS, Windows Bash722723<div class="termy">724725```console726$ which python727728/home/user/code/awesome-project/.venv/bin/python729```730731</div>732733////734735//// tab | Windows PowerShell736737<div class="termy">738739```console740$ Get-Command python741742C:\Users\user\code\awesome-project\.venv\Scripts\python743```744745</div>746747////748749That means that the `python` program that will be used is the one **in the virtual environment**.750751you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell.752753The 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.754755The most important part is that when you call `python`, that is the exact "`python`" that will be executed.756757So, you can confirm if you are in the correct virtual environment.758759/// tip760761It's easy to activate one virtual environment, get one Python, and then **go to another project**.762763And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project.764765It's useful being able to check what `python` is being used. 🤓766767///768769## Why Deactivate a Virtual Environment770771For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment.772773And then you want to work on **another project** `prisoner-of-azkaban`.774775You go to that project:776777<div class="termy">778779```console780$ cd ~/code/prisoner-of-azkaban781```782783</div>784785If 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`.786787<div class="termy">788789```console790$ cd ~/code/prisoner-of-azkaban791792$ python main.py793794// Error importing sirius, it's not installed 😱795Traceback (most recent call last):796 File "main.py", line 1, in <module>797 import sirius798```799800</div>801802But 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`.803804<div class="termy">805806```console807$ cd ~/code/prisoner-of-azkaban808809// 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$ deactivate811812// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀813$ source .venv/bin/activate814815// Now when you run python, it will find the package sirius installed in this virtual environment ✨816$ python main.py817818I solemnly swear 🐺819```820821</div>822823## Alternatives824825This is a simple guide to get you started and teach you how everything works **underneath**.826827There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.828829Once 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>.830831`uv` can do a lot of things, it can:832833* **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 things839840## Conclusion841842If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓843844Knowing 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 lines
71 - 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 lines
modified:README.md+2 added
44 unmodified lines
45**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.4647## Installation4849Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:5051<div class="termy">5253```console54$ pip install typer
330 unmodified lines