DEV Community

jjmuchai
jjmuchai

Posted on

๐Ÿ Python Environment Setup: A Complete Guide to venv and pipenv (with Pytest Testing)

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`
Enter fullscreen mode Exit fullscreen mode

On Windows:

env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

On macOS/Linux:

source env/bin/activate
Enter fullscreen mode Exit fullscreen mode

Install packages

pip install requests
Enter fullscreen mode Exit fullscreen mode

Install pytest for testing

pip install pytest
Enter fullscreen mode Exit fullscreen mode

Freeze dependencies

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

Deactivate when done
โœ… Example Test with pytest
calculator.py

def add(a, b):
    return a + b
Enter fullscreen mode Exit fullscreen mode

test_calculator.py

from calculator import add

def test_add():
    assert add(2, 3) == 5
Enter fullscreen mode Exit fullscreen mode

Run your tests with:

pytest
Enter fullscreen mode Exit fullscreen mode

๐ŸŸฆ 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
Enter fullscreen mode Exit fullscreen mode

Create an environment and install a package

pipenv install requests
Enter fullscreen mode Exit fullscreen mode

Install pytest as a dev dependency

pipenv install --dev pytest
Enter fullscreen mode Exit fullscreen mode

Activate the shell

pipenv shell
Enter fullscreen mode Exit fullscreen mode

Run your tests

pytest
Enter fullscreen mode Exit fullscreen mode

Exit the shell

exit
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช 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
Enter fullscreen mode Exit fullscreen mode

Add this to .gitignore:

env/
.venv/
__pycache__/
.pytest_cache/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)