DEV Community

Cover image for Pipenv, the best way to handle Python Virtual Environments?
Alex Merced
Alex Merced

Posted on

Pipenv, the best way to handle Python Virtual Environments?

Virtual environments have always been one of those areas of constant discovery as I've learned python. I've been writing on articles what, how, and why of Virtual Environments and you can find those articles here:

While all of these work great for isolating dependencies and outputting dependencies to a requirements.txt allow use to track dependencies one piece is still missing, deterministic dependency resolution.

When working with NodeJS or Yarn you may notice a .lock file that gets generated when installing libraries, ever wondered what it did? The lock file not only tracks dependencies but also tracks the dependencies of those dependencies so that way if two libraries you use have the underlying dependency that it isn't downloaded multiple times allowing for a faster installation and more consistent reproduction of your environment.

To have this type of feature in Python we will need to use Pipenv to handle our virtual environments! (yep, another venv option, but quite possibly the best one!)

Setup

First, you got to install pipenv.

pip install pipenv
Enter fullscreen mode Exit fullscreen mode

Generating a Virtual Environment

In any folder that you're creating a project for run the following command (similar npm init)

pipenv shell
Enter fullscreen mode Exit fullscreen mode

This will generate a virtual environment along with the following after you install your first package:

  • pipfile: list of dependencies and package info like Package.json for node or Cargo.toml for Rust
  • Pipfile.lock: File dependency resolution

** Note if you've created a virtual environment in this directory already it will instead activate it instead of creating a new one.

Install Libraries

To install libraries your command will look a little different...

pipenv install packageName
Enter fullscreen mode Exit fullscreen mode

Learn More

Top comments (2)

Collapse
 
darkain profile image
Vincent Milum Jr

To have multiple environments (of which, I have a lot!) I personally opted to use FreeBSD jails instead. Why? Well, for starters, they're language agnostic, so it is one tool that handles any project I may be working on regardless of Python, Node, PHP, C/C++, or otherwise. Plus, it allows bundling non-language packages too, such as a database, or other helper utilities. It also means that the entire environment (all installed applications and utilities) can be easily cloned to another machine with a single command.

Collapse
 
aghost7 profile image
Jonathan Boudreau

Personally I've been using poetry. It isn't really better when it comes to environment management, but there's some other niceties like better package publishing.