Saving and Locking Dependencies with Pipenv
How to save dependencies
To save dependencies in a Pipfile
using pipenv
, you can use the pipenv install
command followed by the package names or requirements file. Here’s the step-by-step process:
-
Activate your project’s virtual environment by navigating to your project’s directory in the terminal and running the command:
pipenv shell
-
Install the desired packages or dependencies using
pipenv install
. You have a few options here:- Install individual packages:
pipenv install package_name1 package_name2 ...
- Install packages from a requirements file (
requirements.txt
):pipenv install -r requirements.txt
- Install packages from a
Pipfile.lock
(if it exists) and update the Pipfile accordingly:pipenv install --ignore-pipfile
The
--ignore-pipfile
flag tells pipenv to ignore the existingPipfile
and only consider thePipfile.lock
for installation.
- Install individual packages:
-
After running one of the above pipenv install commands,
pipenv
will automatically update thePipfile
in your project directory with the installed dependencies and their respective versions. -
The Pipfile will have a section
[packages]
where the installed packages are listed with their versions. For example:[packages] requests = "==2.26.0" numpy = "==1.21.0"
-
Optionally, you can also specify additional settings or constraints for your dependencies in the
Pipfile
. For example, you can set a minimum required version or specify a specific version range. You can manually edit the Pipfile using a text editor to add these settings.Here’s an example of specifying a minimum version for a package:
[packages] requests = ">2.25.0"
Once you’ve made the necessary changes, save the
Pipfile
.
That’s it! The Pipfile
will now contain the list of your project’s dependencies along with their versions.
How to lock dependencies
-
Once you have your Pipfile with the desired dependencies, run the following command to generate the Pipfile.lock:
pipenv lock
This command will analyze the
Pipfile
, resolve the dependency graph, and produce a lock file that specifies the exact versions of all installed packages, as well as their dependencies.The
Pipfile.lock
file will be generated in your project’s directory. It is recommended to commit this file to version control (e.g.,Git
) along with your code. This allows you and your team to have reproducible builds with consistent dependency versions. -
Whenever you install or update packages using
pipenv
, it will consult thePipfile.lock
to ensure that the same versions of packages are installed, providing consistency across different development environments. -
By regularly running pipenv lock and committing the updated
Pipfile.lock
, you can maintain a reliable and reproducible dependency environment for your project.