Setting up a proper Python environment is crucial for writing clean, testable, and maintainable code โ whether youโre building a simple script or a full-scale data science pipeline.
In this article, Iโll break down how to manage your Python environments using two tools: venv (Pythonโs built-in virtual environment tool) and pipenv (a higher-level tool for dependency management). Youโll also learn how to test your code with pytest.
๐น Why Use a Virtual Environment?
A virtual environment isolates your projectโs dependencies from your global Python installation. This prevents conflicts and keeps your project clean and reproducible.
๐ฉ Option 1: Using venv (Built-in)
๐ง Step-by-Step Setup
Create the environment
`python -m venv env
Activate it`
On Windows:
env\Scripts\activate
On macOS/Linux:
source env/bin/activate
Install packages
pip install requests
Install pytest for testing
pip install pytest
Freeze dependencies
pip freeze > requirements.txt
Deactivate when done
โ
Example Test with pytest
calculator.py
def add(a, b):
return a + b
test_calculator.py
from calculator import add
def test_add():
assert add(2, 3) == 5
Run your tests with:
pytest
๐ฆ Option 2: Using pipenv (Modern and Streamlined)
pipenv simplifies dependency management and keeps everything tracked in Pipfile.
๐ง Step-by-Step Setup
Install pipenv
pip install pipenv
Create an environment and install a package
pipenv install requests
Install pytest as a dev dependency
pipenv install --dev pytest
Activate the shell
pipenv shell
Run your tests
pytest
Exit the shell
exit
๐งช Why Use pytest?
Clean syntax with simple assert statements
Fast test discovery
Plugins for coverage, mocking, fixtures, etc.
๐ Suggested Folder Structure
my_project/
โโโ env/ or .venv/ # virtual environment (excluded from Git)
โโโ calculator.py
โโโ test_calculator.py
โโโ requirements.txt or Pipfile
โโโ .gitignore
Add this to .gitignore:
env/
.venv/
__pycache__/
.pytest_cache/
Top comments (0)