Day 14: Virtual Environments and Dependency Management

Day 14: Virtual Environments and Dependency Management

·

2 min read

Welcome to Day 14 of our Python blog series! Today, we'll explore virtual environments and dependency management in Python. These are crucial tools for managing project dependencies and ensuring reproducibility across different environments.

Virtual Environments

A virtual environment is an isolated environment where you can install dependencies and run Python code independently of the system-wide Python installation. This allows you to create and manage project-specific dependencies without affecting other projects or the system environment.

Creating a Virtual Environment

You can create a virtual environment using the venv module.

#creating a virtual environment named 'myenv'
python -m venv ./myenv

Activating a Virtual Environment

Once created, you need to activate the virtual environment before using it.

myenv\Scripts\activate

Installing Dependencies

After creating and activating virtual environment, you can now install any external dependencies that you need, you can install dependencies using pip.

pip install package_name

Dependency Management

Dependency management involves specifying and installing the dependencies required by your Python project. This ensures that your project can run correctly by installing the necessary libraries and versions.

Managing Dependencies with requirements.txt

You can specify project dependencies in a requirements.txt file, listing each dependency on a separate line.

package1==1.0.0
package2>=2.1.0

You can then install all dependencies listed in the requirements.txt file using pip.

pip install -r requirements.txt

Managing Dependencies with pipenv

pipenv is a higher-level tool that simplifies dependency management and virtual environment creation.

#install pipenv
pip install pipenv

pipenv install package_name

#activate the virtual environment
pipenv shell

Conclusion

Day 14, we delved into virtual environments and dependency management in Python. Virtual Environment provide isolated environments for Python projects, enabling separate dependency installations without affecting the system-wide Python setup. Dependency management Involves handling project dependencies to ensure correct functionality and compatibility across different environments.