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)