Preparing Your Virtual Environment: pipenv
Learn how to prepare the virtual environment.
We'll cover the following
Setting up a Python environment
A Python virtual environment allows us to keep the versions of libraries used by our Python application separate from those required by other applications. If one project requires version 1.3 of some library and another requires version 2.1 of the same library, they would conflict. With virtual environments, we can simultaneously set up each project in its own environment on the same machine and eliminate the conflict.
A standard approach for managing virtual environments for Python is to use venv. This is perfectly adequate for the task, but pipenv is preferred, as it combines the Python package manager pip with the virtual environments from venv. It’s easier to use than venv, and it integrates nicely with Heroku for streamlining deployments.
Installing and setting up pipenv
To install pipenv
, we’ll need to use pip (on any OS).
$ pip install pipenv
To create a project, we use the command line to create a directory for that project and enter it. We then call pipenv
and indicate the version of Python we’re using.
PS C:> mkdir frap-api
PS C:> cd frap-api
PS C:> pipenv --three
Using pipenv --three
installs the default version of Python 3
available on our system. If needed, we can specify a particular version with pipenv --python 3.6
. In this course, we stick strictly to Python 3 as the only reason to use Python 2 is to support legacy code.
Creating the pipenv
environment creates a file called “Pipfile” that tracks the packages being used. We can add packages using pipenv
the same way we might use pip
. For example, to add Flask, we use the install
subcommand.
$ pipenv install flask
This installs not only the Flask module but also the modules on which it depends. We can see
the dependencies using the pipenv graph
.
$ pipenv graph
Flask==1.0.2
- click [required: >=5.1, installed: 7.0]
- itsdangerous [required: >=0.24, installed: 1.1.0]
- Jinja2 [required: >=2.10, installed: 2.10]
- MarkupSafe [required: >=0.23, installed: 1.1.0]
- Werkzeug [required: >=0.14, installed: 0.14.1]
This shows that Flask version 1.0.2 is installed and that it depends on the modules for Click, itsdangerous, Jinja2, and Werkzeug. Also, Jinja2 requires MarkupSafe. Typically, pipenv manages this information, so you don’t need to think about it. The only important part is what goes in the Pipfile.
Get hands-on with 1400+ tech skills courses.