techmore.in

Python - Environment

What is a Python Environment?

A Python environment refers to a specific setup that includes the Python interpreter, installed packages, and dependencies used to run Python code. Environments allow you to isolate projects and avoid conflicts between package versions.

Why Use Python Environments?

  • Isolate dependencies for different projects
  • Avoid conflicts between package versions
  • Enable consistent development and deployment
  • Better project organization and maintainability

Types of Python Environments

  • System-wide Environment
  • Virtual Environment (venv)
  • Conda Environment
  • Docker-based Python Environment

1. Creating a Virtual Environment

bash
python -m venv myenv     # Create a virtual environment
source myenv/bin/activate  # Activate (Linux/Mac)
myenv\Scripts\activate     # Activate (Windows)

2. Installing Packages in venv

bash
pip install numpy requests  # Install packages inside virtual environment
pip freeze > requirements.txt  # Save environment packages

3. Using Conda Environment

conda is a package manager that comes with Anaconda or Miniconda distributions.

bash
conda create -n myenv python=3.11
conda activate myenv

4. Viewing Installed Packages

bash
pip list            # For venv
conda list          # For conda

5. Deactivating and Removing Environments

bash
deactivate                    # Exit venv
conda deactivate              # Exit conda env
conda remove --name myenv --all  # Delete conda env

6. Using requirements.txt

You can recreate environments using a requirements.txt file.

bash
pip install -r requirements.txt

7. Best Practices

  • Create a virtual environment for each project
  • Use requirements.txt for reproducibility
  • Use Anaconda if working with data science tools
  • Avoid installing packages in system Python

8. Checking Python Version

bash
python --version

Conclusion

A well-managed Python environment is crucial for scalable development and debugging. Whether using venv, conda, or Docker, isolating dependencies ensures clean, consistent, and secure project builds.