virtual-environments.md
This file
Path
docs/virtual-environments.md
844 lines · 21.7 KiB · Markdown
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 0b6a405 point at it.
📝 Update release notesgithub-actions[bot]before adoption0b6a405
lines 1–844why, one step back1# 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 its 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**. 😎