Integrated Python Development with pipenv

Python3

Python has a few problems. There are two main version that conflict with each other, python may mean python3 in one system or python2 in other. Different ways to install packages using pip, easy_install, or system package manager. Packages may conflict with each other in unexpected ways or use the same import name.

A common solution to this is to use virtualenv (Virtual Environment). Virtualenv creates an isolated project environment that contains the right version of python and package dependencies without affecting other projects. However, You still have to manually install the package dependencies for each project environment. At least until pipenv.

Pipenv integrates virtualenv and pip to create a modern python development environment that easily manage dependencies. Similar to development environment used by Android (Gradle), JavaScript (NPM) and Rust (Cargo) developers.

The installation of pipenv is straightforward:

sudo pip3 install pipenv

Pipenv work per project basis like other development tools. To create a pipenv project:

cd <project>
pipenv install

It create two files:

Pipfile that contains meta information and list of package dependencies.

# Pipfile
[source]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]

[requires]
python_version = "3.8"

Pipfile.lock: Lock file with information about installed packages.

# Pipfile.lock
{
    "_meta": {
        "hash": {
            "sha256": "..."
        },
        "pipfile-spec": 6,
        "requires": {
            "python_version": "3.8"
        },
        "sources": [
            {
                "name": "pypi",
                "url": "https://pypi.org/simple",
                "verify_ssl": true
            }
        ]
    },
    "default": {},
    "develop": {}
}

For example, to add paho-mqtt as a project dependencies:

pipenv install paho-mqtt

To run a session with the environment loaded:

# Shell
pipenv shell

# Python Shell
pipenv run python

# Python program
pipenv run python script.py

For more information check the documentation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s