A Guide to Creating Virtual Environments in Python

Photo by David Clode on Unsplash

A Guide to Creating Virtual Environments in Python

Step 1: Install virtualenv (if not already installed)

pip install virtualenv

Step 2: Create a Virtual Environment

Navigate to your project directory in the terminal and run:

virtualenv venv

Here, venv is the name of your virtual environment, but you can choose any name you prefer.

Step 3: Activate the Virtual Environment

On Unix or MacOS:

source venv/bin/activate

You'll know the virtual environment is activated when you see its name in your terminal prompt.

In case you are using fish shell

Activate the Virtual Environment: In the Fish shell, you use the command source venv/bin/activate.fish to activate the virtual environment. The command you provided source venv/bin/activate is typically used in Bash. For Fish, the script is slightly different.

So, your command in the Fish shell should be:

source venv/bin/activate.fish

Step 4: Install Dependencies

Now that your virtual environment is active, you can install the required packages using pip.

pip install package_name

Step 5: Deactivate the Virtual Environment

When you're done working on your project, deactivate the virtual environment.

deactivate

Why Virtual Environments?

Let's understand why virtual environments are crucial for Python development.

  1. Isolation: Virtual environments provide a sandbox for each project, isolating its dependencies from the global Python environment. This isolation ensures that changes made to one project won't affect others.

  2. Dependency Management: Projects often require specific versions of libraries or packages. Virtual environments make it easy to manage dependencies and avoid version conflicts between projects.

  3. Cleaner Development Workflow: With virtual environments, you can create a clean slate for each project, making it easier to track and share the exact set of dependencies required to run your code

If you liked this blog, you can follow me on twitter, and learn something new with me.