A Small Room for Each Project: Python Virtual Environments and Packaging
Project A wants the new requests, project B only works with the old one — one system Python cannot hold both. From venv creation and activation through pip installs to pyproject.toml and python -m build, then verifying editable and wheel installs with a bookstore command. Every command tested.

You have two small Python projects. Project A needs the new version of requests, and project B's old code only works with the old version. Both share one system Python: install the new version and you break B; install the old one and A will not run. That is the problem virtual environments solve: give each project its own small room, install each one's packages separately, and keep them out of each other's way.
This guide covers how to build a room, install packages inside it, and turn your own project into a package other people can pip install. The example is the same fictional Morning Light Bookstore ledger script from earlier guides in this series, packaged here as morning-bookstore. Every command below was run and verified on Python 3.12.3.
Before reading, you only need to know your way around a terminal and have Python 3.9 or newer installed. Earlier guides in this series covered variables, functions, modules, classes, and exception handling, and a little of that shows up here — but you can follow along even without all of it, because every step has a command you can copy and real output to compare against. If your output does not match, something drifted off course at that step, and you can look back from there.
1. What a virtual environment actually is
A virtual environment is a folder. Inside it there is an entry point to a Python interpreter, its own site-packages directory (where third-party packages live), and a small pyvenv.cfg file recording which system Python it was created from. It does not copy all of Python; it just borrows the base interpreter, so creating one takes seconds.
Three things matter. First, the python inside the environment and the system python are the same interpreter, so the version does not change. Second, packages installed with pip go only into the current environment's site-packages; other environments cannot see them. Third, the environment holds no project code — the code lives in your project folder, and the environment can be deleted and rebuilt at any time.
Python has shipped the venv module since version 3.3, so nothing extra needs installing. There is also an older third-party tool called virtualenv with more features (it can build Python 2 environments, for example, and is a little faster), but the built-in venv is enough to start with — learn it well first.
2. Create an environment in three commands
Go into your project folder and run:
python3 -m venv .venv
This creates a .venv folder in the project. The name .venv (or venv) is a convention; the dotted form is more common because many tools treat it as a hidden folder. Peek inside at pyvenv.cfg and you will see it recorded where the base Python lives, for example home = /usr/bin, version 3.12.3. If you juggle several environments in one project, give the prompt a name when you create it, for example python3 -m venv .venv --prompt bookstore — after activation the prefix shows (bookstore) instead of (.venv), so you can tell at a glance which project you are in.
Then activate it. Activation simply puts the environment's bin directory at the front of your shell's PATH, so typing python finds the one inside the environment:
source .venv/bin/activate
After activation your prompt gains a prefix like (.venv) — that is the sign you are inside the environment. Type deactivate when you are done and the prefix goes away. The activation command differs by system and shell, so copy from this table:
| System | Shell | Command to activate |
|---|---|---|
| macOS / Linux | bash / zsh | source .venv/bin/activate |
| macOS / Linux | fish | source .venv/bin/activate.fish |
| Windows | cmd.exe | .venv\Scripts\activate.bat |
| Windows | PowerShell | .venv\Scripts\Activate.ps1 |
On Windows, the first run of Activate.ps1 may be blocked by the execution policy; the official docs suggest running Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser once. One thing many people do not know: you do not have to activate at all. You can use the full path, for example .venv/bin/python script.py, and get exactly the same result — editors and automation scripts often do it that way.
What does activation actually change? Just two small things: it adds the environment's bin directory to the front of PATH, and it sets a VIRTUAL_ENV environment variable recording where the environment lives. Running deactivate restores both. Your system Python is not touched at all, so activation cannot really break anything — the worst case is installing something in the wrong place, and rebuilding an environment fixes that.
3. How to check you are inside the environment
The prompt prefix alone is not reliable, because it can be changed. The surest check is to ask Python itself:
python -c "import sys; print(sys.prefix != sys.base_prefix)"
Run inside an environment, this prints True; run under the system Python, it prints False. The logic is simple: inside an environment, sys.prefix points at the environment directory while sys.base_prefix still points at the base Python. If they differ, you are in an environment. This line is worth memorizing — whenever a package is "installed but cannot be imported", run it first; nine times out of ten you are running the wrong Python.
While you are at it, look at what is installed:
python -m pip list
A fresh environment holds only pip and setuptools and a couple of companions — not even requests. That clean starting point is exactly what we want. Note that I wrote python -m pip, not a bare pip; the section on pitfalls explains why.
4. Installing packages inside the environment: the basic pip moves
Installing is pip's job. Inside an activated environment:
python -m pip install requests
The last line of the real output was Successfully installed certifi-2026.11.20 charset_normalizer-3.5.2 idna-3.20 requests-2.34.2 urllib3-2.8.0. Note that requests did not come alone; it brought the small packages it depends on. After installing, python -c "import requests; print(requests.__version__)" printed 2.34.2, matching what was just installed.
The first thing to do in a new environment is usually to upgrade pip itself:
python -m pip install --upgrade pip
An old pip sometimes fails in strange ways on new packages, and upgrading saves a lot of trouble. To check where a package actually landed, use pip show and look at its location:
python -m pip show requests
One line reads Location: /tmp/venv238-test/.venv/lib/python3.12/site-packages — the path contains .venv, which proves it went into the environment rather than the system. That Location line is the most direct evidence when you suspect a package went to the wrong place, more useful than scrolling through pip list. Then export the list of installed packages, so someone else — or you, three months from now — can rebuild an identical environment from the list:
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt
A freeze output in requirements.txt looks like this, one package per line with a pinned version:
requests==2.34.2
urllib3==2.8.0
...
We verified this by reinstalling from that list into a brand-new environment: requests came back as 2.34.2, exactly as pinned. This file belongs in Git. The .venv folder absolutely does not — the environment is a disposable thing that can be rebuilt; the list is the real record. Python 3.13 and later automatically add a .gitignore to a new .venv; on 3.12 and earlier, add a line .venv/ to your own .gitignore.
5. Four mistakes everyone makes
Mistake 1: forgetting to activate, so the package lands in the system Python. The symptom is that pip list shows it but running the script raises ModuleNotFoundError. Run the sys.prefix check above first; if it prints False, you were never inside the environment. You can also ask the system which Python it is using: which python on macOS and Linux, where python on Windows — the printed path should sit inside your .venv. Activate, then install again. Remove the copy that went into the system Python with the system Python's pip uninstall so it does not linger and cause confusion.
Mistake 2: pip and python are not a pair. A machine can have a system Python, a Python from python.org, and one bundled with an editor, each with its own pip. The pip you invoke with pip install is not necessarily the one that belongs to the python you run. The cure is to always write python -m pip: the -m flag means "use this python's own pip", so the two cannot mismatch.
Mistake 3: committing the whole .venv to Git. Hundreds of megabytes of binaries go into the repository, and nobody else can use them anyway, because the scripts inside record absolute paths from your machine. Commit only requirements.txt and pyproject.toml, and let everyone build their own environment.
Mistake 4: moving or copying the environment folder. The scripts inside an environment start with absolute paths, so moving the whole folder breaks all of them. The right move is to delete the old one, run python -m venv .venv in the new location, and reinstall with pip install -r requirements.txt. Remember: an environment is a consumable, not a piece of furniture.
6. From a script to an installable package: lay out the folders first
So far our bookstore script is still a single .py file, and anyone who wants it has to copy the file over. Why bother packaging at all? Imagine sending the script to a friend: they have Python installed, but they do not know the command line and would not know which dependency to install first. Send them the bare .py file and it will most likely fail with a missing package; send them a wheel and they only need to pip install that file, then type bookstore. Packaging turns "works on my machine" into "works on their machine too", without them needing to understand your project structure. To make it pip install-able, first arrange it as a package. The src layout recommended by the official packaging tutorial looks like this:
bookstore-pkg/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│ └── bookstore/
│ ├── __init__.py
│ └── cli.py
└── tests/
The advantage of the src layout: when you run tests from the project root, Python will not mistake the unpackaged source for the installed package, so you test what users actually install. The tests/ folder can stay empty for now; it just holds the place. One detail: src/bookstore/__init__.py can be an empty file, and its job is to tell Python "this folder is a regular package that can be imported". Without it the folder is only a namespace package, and build tools may not treat it as a regular package, which is why the packaging tutorial recommends keeping the empty file.
Our cli.py is only a few dozen lines — a trimmed-down version of the Morning Light Bookstore ledger script from earlier guides in this series:
"""Command-line entry point for the bookstore example."""
BOOKS = [
("Python Basics", 59),
("Python Advanced", 79),
]
def total_value(books=None):
"""Return the total price of the given (title, price) pairs."""
books = BOOKS if books is None else books
return sum(price for _title, price in books)
def main():
print(f"Morning Bookstore has {len(BOOKS)} books, total {total_value()} yuan.")
if __name__ == "__main__":
main()
Two books, 59 plus 79, a total of 138 yuan. Keep that number in mind — it is the answer we will check against once the package is installed.
7. Writing pyproject.toml: the package's ID card
pyproject.toml is the standard configuration file for packaging today. One file handles two jobs: what the package is called, and which tool builds it. Here is the exact file that built successfully in our test:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "morning-bookstore"
version = "0.1.0"
description = "A tiny bookstore inventory helper used as a packaging example"
readme = "README.md"
requires-python = ">=3.9"
license = "MIT"
authors = [
{ name = "Example Author", email = "author@example.com" },
]
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
]
[project.scripts]
bookstore = "bookstore.cli:main"
Field by field. [build-system] tells the packaging tools which backend does the work — here Hatchling, light and the default recommendation. Setuptools works too; just change two lines, requires = ["setuptools >= 77"] and build-backend = "setuptools.build_meta", and we verified it builds the same package. [project] holds the metadata: name is the name on PyPI, version is the version, requires-python states the oldest Python supported, and readme and license point at files in the project. Do not leave license blank: without a license, others legally cannot reuse your code even if you put it online in public; MIT is the most common permissive choice, meaning others may use, change, and sell it as long as they keep your copyright notice. The classifiers are for PyPI's categorization — copying the two lines above is enough until the package grows.
[project.scripts] is the most useful part: it says "once this package is installed, give the user a command called bookstore that runs the main function in bookstore.cli". After installing, you just type bookstore in the terminal instead of python xxx.py.
There is one easy trap here, and our test run hit it: the distribution name and the import name can differ. Our distribution name is morning-bookstore (with a hyphen), while the importable package is the folder bookstore. Hatchling looks by default for a folder matching the distribution name, and failing that it errors out with Unable to determine which files to ship inside the wheel. The fix is three lines at the end of the file, stating plainly which folder to ship:
[tool.hatch.build.targets.wheel]
packages = ["src/bookstore"]
After adding those three lines the build went through. If you use Setuptools as the backend, the equivalent is [tool.setuptools.packages.find] with where = ["src"], which we also verified builds. Keeping the names identical is simplest, but knowing this fix means a project with different names will not leave you stuck.
8. Building: python -m build
First install the build tool itself (inside the environment, not the system):
python -m pip install build
python -m build
python -m build installs a fresh copy of the backend into an isolated environment, then produces two files in a dist/ folder. "Isolated environment" means build creates a separate temporary clean environment, installs the backend listed in [build-system]'s requires, and only then starts working — completely separate from the development environment you are sitting in. The benefit: anyone who receives your project can build the same package from pyproject.toml alone, without guessing which build tools you happen to have installed. The last line of our real output was:
Successfully built morning_bookstore-0.1.0.tar.gz and morning_bookstore-0.1.0-py3-none-any.whl
The two files have different jobs. The .tar.gz is the source distribution (sdist): it contains your source code. The .whl is a wheel, a pre-arranged installable archive, and pip installs it fastest. When uploading to PyPI, send both: a new pip prefers the wheel and falls back to building from the sdist if the wheel cannot be used. Note the hyphen became an underscore in the filenames (morning_bookstore); that is the packaging convention, and it is still the same package.
9. Installing the package you just built
During development the most common move is an editable install:
pip install -e .
The -e stands for editable: after installing, import bookstore points at the source you are editing, so a one-line change takes effect immediately without rebuilding. In our test, typing bookstore right after installing printed exactly the line we predicted:
Morning Bookstore has 2 books, total 138 yuan.
Then verify with the wheel in a completely fresh, empty environment:
python -m venv .venv3
.venv3/bin/python -m pip install dist/*.whl
.venv3/bin/bookstore
The output was the same Morning Bookstore has 2 books, total 138 yuan., and pip show morning-bookstore showed version 0.1.0 with the author information. Use -e . while developing and the wheel for other people — once both paths work, the package is done. Removing it again is just as easy: pip uninstall morning-bookstore, and pip lists the files it will delete for you to confirm first. Uninstalling and reinstalling a practice package a few times is perfectly normal, so do not feel precious about it.
10. Want to share it? Practice on TestPyPI first
Installing locally is not the same as publishing to the world. PyPI (the Python Package Index) is the big repository behind pip install. For a first release, do not go straight to real PyPI — practice on TestPyPI, the test instance: register an account, install twine, and upload:
python -m pip install twine
python -m twine upload --repository testpypi dist/*
After uploading, install it back from the test index to check it really works:
pip install --index-url https://test.pypi.org/simple/ morning-bookstore
Only then upload to real PyPI. Two warnings: first, package names are first come, first served — a name like morning-bookstore may well be taken already, so search PyPI before uploading. Second, a version number can only go up: once 0.1.0 is uploaded, you cannot upload 0.1.0 again; change something and move to 0.1.1. Versions usually follow "semantic versioning": the last number is for small fixes (0.1.0 to 0.1.1), the middle one for new features that keep old usage working (0.1.0 to 0.2.0), and reaching 1.0.0 generally means the author considers the package stable enough to rely on.
11. venv, conda, or uv — which one to pick
Searching for virtual environments turns up a pile of names, which is confusing for a beginner. The short answer: learn the official combination first — venv + pip + pyproject.toml — and look at the others later.
venv ships with Python and does exactly one job, "install packages into a separate folder". It is simple and transparent: when something goes wrong you can open the folder and see what happened. conda is a bigger system that can also install non-Python things (such as the C libraries data science and machine learning rely on), and it is common in those circles; the price is that it has its own commands and its own package repository, different from pip, which is easy to mix up when you are starting out. uv, poetry, and pipenv are higher-level tools that bundle environment creation, version locking, and packaging into one workflow, and they are faster too — but underneath they still do the same thing: build a virtual environment and install packages into it. Once you have walked the whole flow by hand with venv, switching to one of these is easy, and when something breaks you will know which layer to look in.
One more common question: what is the difference between requirements.txt and the dependencies field in pyproject.toml? The requirements.txt file is a "rebuild my environment exactly as it is" list, used for development and deployment, with versions pinned hard. The dependencies in pyproject.toml say "these are the other packages my package needs at runtime", written for the people who install your package, and versions there usually only state a lower bound, for example dependencies = ["requests >= 2.28"]. One rebuilds an environment, the other declares dependencies — different jobs, and a finished project needs both.
12. Quick answers
Can one environment hold several Python versions? No. A virtual environment inherits the version of the Python it was built from. To use Python 3.11 and 3.12, install both Pythons on the machine first, then build one environment from each. Tools for managing several Python versions are called pyenv, or you can simply install multiple versions from python.org.
What if pip install is very slow? It is often the network. You can point pip at a mirror closer to you for one install, for example python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests. That is just an example — any mirror you trust works; if you like it, put it in pip's configuration file so you do not have to add the flag every time.
What if an environment gets broken? Delete it and rebuild. That is the biggest advantage of virtual environments: rm -rf .venv, then run python3 -m venv .venv and pip install -r requirements.txt again, and you are back to a clean state in minutes. When an environment misbehaves, first ask whether rebuilding is faster than fixing it.
13. Checklist
For your next project, walk through this list: new folder, python3 -m venv .venv, activate, python -m pip install --upgrade pip, install dependencies, pip freeze > requirements.txt, and add .venv/ to .gitignore. When it is time to package, add: arrange the src layout, write pyproject.toml, run python -m build, install the wheel in a fresh environment to verify, and only then think about TestPyPI.
Virtual environments and packaging really come down to two things: while developing, do not mix other people's projects with your own; when publishing, do not make other people guess how to install your code. Rooms separated, package built — the rest is just writing code. Following this series' plan, the next guide should cover pytest testing — and this bookstore package will make a handy thing to test.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.
A README full of commands pasted by hand will go wrong one day. With 5 notes: 15 lines merged into a 17-line page, checks passed 3/3, a second make prints only Nothing to be done, and spaces instead of a Tab fail with missing separator. GNU Make 4.3.