A Comprehensive Guide To Python Dependency Management (2024)

Python dependency management is essential to the well-being of your projects. If your Python application relies on third-party libraries and frameworks to function, properly managing them can help you reap the rewards of security, sustainability, and consistency.

If you manage your direct dependencies and transitive dependencies well, you could produce a performant and quality application. It’s what you need to take your Python development efforts to the next level.

This article talks about how to manage Python dependencies. We’ll demonstrate how you can use the popular pip tool for managing dependencies in Python. We’ll also go over some alternatives in case pip does not meet your use case needs.

Contents hide

Getting Started With pip

Installing Packages With pip

Uninstalling Packages With pip

Upgrading A Package

Using A Requirements File

Alternatives To pip

How Do You Detect Vulnerabilities In Projects?

Getting Started With pip

pip (package installer for Python) is the default tool used for managing packages in Python. It comes preinstalled with Python version 2.7.9 (or later) and Python version 3.4 (or later). If you’re using an older Python version, you can follow the instructions for installing pip here.

If you’ve used package management tools in other languages, such as Node.js’ npm, pip is similar in spirit to those.

You can run the following command on your console to confirm that pip is available on your machine:

pip –version

Here is an example:

PS C:\Users\User> pip –version
pip 20.2.3 from c:\users\user\appdata\local\programs\python\python39\lib\site-packages\pip (python 3.9)

As you can see above, the command outputs the pip version alongside the location and version of Python installed on your machine.

Installing Packages With pip

Python is generally considered as a battery included language; that is, it has a rich collection of packages and modules you can use to make a wide variety of tasks easy and fast.

Similarly, Python has a robust community of contributors that creates an even larger set of packages. These libraries, tools, and frameworks are primarily published on PyPI (Python Package Index). There are also other public and private sources for hosting Python packages.

You can use pip to easily download and install dependencies. By default, the tool downloads packages from PyPI.

Here is how to install a package:

pip install <package_name>

The above command searches for the latest version of the specified package and installs it. It also looks for dependencies available in the package metadata and installs them as well. This ensures that the package has all the requirements for functioning optimally.

If you want to install a specific package version for whatever reason, use the equality operator (==) and mention the version number to install:

pip install <package_name>==<version_number>

For example, let’s see how you can install the download module for easily downloading files from the web:

pip install download

If you want to install a specific version, run the following command:

pip install download==0.3.2

Once it is installed, you can import and use it in your project:

Here is an example:

from download import download
path = download(add_url, add_file_path)

Uninstalling Packages With pip

Before removing a package, it’s important to check its list of dependencies. If you remove a package that others are using, you may bring your application to its knees.

You can start by using the list command to list all the packages available on your system:

Here is an example:

PS C:\Users\User> pip list
Package Version
———— ———
certifi 2020.12.5
chardet 4.0.0
click 7.1.2
download 0.3.5
Flask 1.1.2
MarkupSafe 1.1.1
pip 20.2.3

Next, use the show command to get more information about an installed package, especially its list of dependencies.

Here is an example:

PS C:\Users\User> pip show download
Name: download
Version: 0.3.5
Summary: A quick module to help downloading files using python.
Home-page: https://github.com/choldgraf/download
Author: None
Author-email: None
License: BSD (3-clause)
Location: c:\users\user\appdata\local\programs\python\python39\lib\site-packages
Requires: tqdm, requests, six
Required-by:

As you can see above, the last two fields, Requires and Required-by, give the package’s list of dependencies. In this case, the download package requires three other dependencies, but it’s not required by any other package. So, it’s safe to remove it.

After understanding the dependency order of your packages, and determining the ones safe to remove, you can use the uninstall command to uninstall them.

pip uninstall <package_name>

Here is an example:

PS C:\Users\User> pip uninstall download
Found existing installation: download 0.3.5
Uninstalling download-0.3.5:
Would remove:
c:\users\user\appdata\local\programs\python\python39\lib\site-packages\download-0.3.5.dist-info\*
c:\users\user\appdata\local\programs\python\python39\lib\site-packages\download\*
Proceed (y/n)? y
Successfully uninstalled download-0.3.5

Notice that pip will ask you to confirm whether you want to uninstall the package. If you want to suppress the confirmation and the file list, just add the -y flag.

pip uninstall <package_name> -y

Here is an example:

PS C:\Users\User> pip uninstall download -y
Found existing installation: download 0.3.2
Uninstalling download-0.3.2:
Successfully uninstalled download-0.3.2

If you want to uninstall several packages, you can specify their names in a single call:

pip uninstall <package_name> <package_name> <package_name>

Upgrading A Package

If you want to update to a newer package version, use the following command:

pip install <package_name> –upgrade

The above command will uninstall the old package version and install the latest version available.

Here is an example:

PS C:\Users\User> pip install download –upgrade
Collecting download
Using cached download-0.3.5-py3-none-any.whl (8.8 kB)
….
Installing collected packages: download
Attempting uninstall: download
Found existing installation: download 0.3.2
Uninstalling download-0.3.2:
Successfully uninstalled download-0.3.2
Successfully installed download-0.3.5

Using A Requirements File

A requirements file allows you to define the packages and their specific versions required for running a project. By convention, the file is named requirements.txt, but you can provide any name you want.

Here is an example of a requirements.txt file:

certifi>=2020.11.0
chardet==4.0.0
click>=6.5.0, <7.1
download==0.3.5
Flask>=1.1.0

As you can see above, you should define each package on its own line in the text file. You should also use logical operators to stipulate the specific version of the package.

With a requirements file, you can replicate the environment in another system without causing breakages. The file ensures that the specified package versions are installed just as they’re defined in the requirements file.

For example, the == operator tells pip that only the specific version can be installed while >= stipulates that an exact or greater version can be installed. In the case of the click package above, pip can install any version equal or greater than 6.5.0, but less than 7.1.

If you want to install the packages specified in the requirements file, run the pip install command while using the -r flag to denote the requirements file.

Here is the command:

pip install -r requirements.txt

The requirements file also allows you to update multiple packages at once. You can use the install command with the –upgrade flag to update all the packages listed on it.

Here is the command:

pip install –upgrade -r requirements.txt

You can also remove all the packages provided in a requirements file. Here is the command:

pip uninstall -r requirements.txt -y

Alternatives To pip

Although pip is a great tool for Python dependency management, there are other tools you can use to effectively manage packages.

Here are two tools you can consider if pip does not meet your use case:

  • Pipenv—this is a higher-level tool that comes with several bells and whistles to make dependency management for common use cases smooth and fast. Whereas pip is usually appropriate for personal projects, Pipenv is mostly recommended for collaborative projects. A notable differentiating feature is that Pipenv uses Pipfile and Pipfile.lock, instead of requirements.txt, to ensure comfortable deterministic builds.
  • Poetry—this option for dependency management lets you declare the libraries your project relies on so that it can install, uninstall, and update them for you. Like Pipenv, it makes Python package dependencies management simpler and straightforward. You can use it to manage your projects in a deterministic manner, build and package your projects using one command, and easily publish to PyPI. It uses the pyproject.toml file for orchestrating your project as well as its dependencies.

How Do You Detect Vulnerabilities In Projects?

Managing dependencies when building Python applications can ensure you have stable, predictable builds across different environments.

But how do you know if there are any security vulnerabilities in your Python dependencies?

Mend offers powerful free developer tools to help you automatically find and fix vulnerabilities in your open source dependencies. You can use the tools to get real-time vulnerability alerts, perform automatic dependency updates, and complete several other tasks.

The Mend security tools seamlessly integrate with your Python development environment. This way, you can focus on building your applications while Mend does the heavy lifting on your behalf.

With the security tools, you can be sure of shipping secure, performant, and stable Python applications. They enable you to consume open source software fearlessly and freely.

Contact us today to learn more about the tools.

A Comprehensive Guide To Python Dependency Management (2024)

FAQs

What is the best way to manage dependencies in Python? ›

Using venv and pipenv are two methods of managing dependencies in Python. They are simple to implement and, for most users, adequate solutions for handling multiple projects with different dependencies. However, they are not the only solutions. Other services can complement their use.

How does pip manage dependencies? ›

Pip relies on package authors to stipulate the dependencies for their code in order to successfully download and install the package plus all required dependencies from the Python Package Index (PyPI). But if packages are installed one at a time, it may lead to dependency conflicts.

How do Python dependencies work? ›

Dependencies are all of the software components required by your project in order for it to work as intended and avoid runtime errors. You can count on PyPI (the Python Package Index) to provide packages that can help you get started on everything from data manipulation to machine learning to web development, and more.

How to package Python code with dependencies? ›

If your project has a dependency requirement that is not currently in the Python Package Index (PyPI), you can still include them if they can be accessed via http and are packaged as either an egg, . py file, or a VCS (Version Control System) repository, such as Git or Subversion.

How many dependencies is too many? ›

The fact your class has so many dependencies indicates there are more than one responsibilities within the class. Often there is an implicit domain concept waiting to be made explicit by identifying it and making it into its own service. Generally speaking, most classes should never need more than 4-5 dependencies.

How do you solve a dependency problem? ›

When these dependency errors occur, we have multiple options we can try to address the issue.
  1. Enable all repositories.
  2. Update the software.
  3. Upgrade the software.
  4. Clean the package dependencies.
  5. Clean cached packages.
  6. Remove "on-hold" or "held" packages.
  7. Use the -f flag with the install subcommand.
  8. Use the build-dep command.
May 21, 2020

What are the 3 types of dependencies? ›

Here are the most common types of task dependencies:
  • Finish to Start (FtS): This is the most common task dependency. ...
  • Finish to Finish (FtF): Task B cannot finish until Task A is also completed. ...
  • Start to Start (StS): Task B cannot start before Task A starts.

What are the three main types of dependencies? ›

3 relationship dependency types in project management
  • Causal relationships. In a causal dependency, one element always depends on another. ...
  • Resource constraint relationships. ...
  • Preferential relationships.
Aug 18, 2021

What are the four types of task dependencies? ›

The four types are as follows – Finish to Start, Finish to Finish, Start to Start, and Start to Finish.

How do you write dependencies in Python? ›

There are two ways to specify dependencies for Cloud Functions written in Python: using the pip package manager's requirements. txt file or packaging local dependencies alongside your function. Dependency specification using the Pipfile/Pipfile.

How do you explain dependencies? ›

A dependency describes the relationship among activities and specifies the particular order in which they need to be performed. Dependencies arise in every decision making, planning and developing process and are ideally predetermined.

Why is Python dependency management? ›

Python dependency management is essential to the well-being of your projects. If your Python application relies on third-party libraries and frameworks to function, properly managing them can help you reap the rewards of security, sustainability, and consistency.

How do I check dependencies in Python? ›

Pip Check Command – Check Python Dependencies After Installation. Because pip doesn't currently address dependency issues on installation, the pip check command option can be used to verify that dependencies have been installed properly in your project. For example: $ pip check No broken requirements found.

How do I install all dependencies in Python? ›

In this case, you have two options: Use the pipdeptree utility to gather a list of all dependencies, create a requirements. txt file listing all the dependencies, and then download them with the pip download command. Get the list of dependencies for a package from the setup.py file.

How do I install project dependencies in Python? ›

Installing dependencies with PyCharm

Install the poetry plugin. Navigate to Project Interpreter , then click the gear icon and click Add . Click Poetry Environment , then click OK . PyCharm will automatically install the packages required into a virtual environment.

Which dependency is the most common? ›

The most common dependency relationship is a finish-to-start relationship. Task P (predecessor) must be finished before task S (successor) can start. The least common relationship is the start-to-finish relationship.

What are the two types of dependency? ›

The dependence classification has two main categories — physical and psychological dependency. Physical dependency means the body has developed a physical reliance on a substance because it alters the body's natural state. Alcohol and nicotine commonly cause physical dependence.

What are the consequences of dependency? ›

Dependency can lead to feelings of depression, agitation, anger, and anxiety. These impact the user and everyone else around him or her. Drug use also heightens the risk of communicable disease and can worsen existing mental health conditions.

How do you manage dependencies in your code? ›

You can add package dependency into the application in two simple ways in Xcode 11.
  1. Adding package dependency from File menu. Open Project File -> Swift packages -> Add package dependency. Add Repository URL and click on Next. ...
  2. Using Build Phases. Open Build Phases - > Link Binary and Libraries -> Click on (+)
Oct 24, 2019

What are the three parts I need to know for a dependency? ›

A dependency relation has three widely-accepted core qualities: (i) a binary relation between two linguistic elements, (ii) an asymmetric relation in which one element is a governor whereas the other serves as a dependent, (iii) a label on the top of an arc linking two elements (Liu, 2009) .

What is a dependency solver? ›

In a nutshell, a dependency solver takes as input: (1) the current status of packages installed on a given system, (2) a universe of all available packages, (3) a user request (e.g., “install the aiohttp library”), and (4) explicit or implicit user preferences (e.g., “only install strictly required packages” v.

What are examples of dependencies? ›

Project Dependency Examples by Type and Industry
Construction
Cross-TeamConstruction Plumbing and electrical teams must complete their installations before the drywall team can close up the walls.
ExternalConstruction Inclement weather, such as rain or snow, might delay the building schedule.
3 more rows
Jul 20, 2022

What are dependencies coding? ›

What is a Dependency? In today's software development world, a dependency is additional code that a programmer wants to call. Adding a dependency avoids repeating work already done: designing, writing, testing, debugging, and maintaining a specific unit of code.

What are dependencies in programming example? ›

A software dependency is a code library or package that is reused in a new piece of software. For example, a machine learning project might call a Python library to build models. The benefit of software dependencies is that they allow developers to more quickly deliver software by building on previous work.

What are examples of start to start dependencies? ›

A SS or Start to Start dependency says that the successor activity can't start unless the predecessor activity has been initiated. But after this initial constraint, the two activities can proceed in parallel. For example, baking the cake and making the icing are an example of a start to start dependency.

Why is dependency management important? ›

The Importance of Dependency Management

Managing dependencies is critical when it comes to handling and finishing all the related processes of a project. This helps to: Prioritize tasks, resources, and activities so that the most important ones are handled first, leading to optimum allocation of resources.

What are the 5 stages of task management? ›

The 5 phases of project management

Project initiation & conception. Project planning. Project execution. Project monitoring & control.

How many types of data dependencies exist? ›

There are three types of dependencies: data, name, and control.

What is the difference between constraints and dependencies? ›

However, the two concepts are not the same, as dependencies are about the order or sequence of tasks. Whereas constraints are limitations to the project, such as the limited availability of resources like time and funds. A huge part of a project manager's job is to balance project constraints.

How do you make a dependency tree in Python? ›

One easy way of doing so is to use the pipdeptree utility. The pipdeptree works on the command line and shows the installed python packages in the form of a dependency tree.

How do you resolve dependency conflicts in Python? ›

You can use pipx. pipx will do all the work of setting up separate virtual environments for each application, so that all the applications' dependencies remain separate. If you use virtualenv yourself, you have to switch environments to run a different application.

What are the 3 types of dependencies in project management? ›

There are several different types of dependencies in project management:
  • Finish-to-Start: Task B cannot start until task A has been completed.
  • Start-to-Start: Task B cannot start until task A starts.
  • Finish-to-Finish: Task A cannot be completed until task B is completed.

Why does NASA use Python? ›

Python is the most common programming language that folks in the astronomy field utilize, because it's “the language of data analysis, data manipulation, and data inference,” Nitya says.

What are the six main reasons that people choose to use Python? ›

Why is Python so Popular?
  • 1) Easy to Learn and Use. ...
  • 2) Mature and Supportive Python Community. ...
  • 3) Support from Renowned Corporate Sponsors. ...
  • 4) Hundreds of Python Libraries and Frameworks. ...
  • 5) Versatility, Efficiency, Reliability, and Speed. ...
  • 6) Big data, Machine Learning and Cloud Computing. ...
  • 7) First-choice Language.
Sep 29, 2022

How do you identify data dependency? ›

Consider two instructions ik and ii of the same program, where ik precedes ii. If ik and ii have a common register or memory operand, they are data-dependent on each other, except when the common operand is used in both instructions as a source operand. An example is when ii uses the result of ik as a source operand.

How can I see object dependencies? ›

Use the Object Dependencies pane
  1. Open the database that you want to investigate.
  2. In the Navigation Pane, select or open a table, form, report, or query.
  3. On the Database Tools tab, in the Relationships group, click Object Dependencies.
  4. If prompted, click OK to update the dependency information.

How do I add library dependencies? ›

Library dependencies can be added in two ways:
  1. unmanaged dependencies are jars dropped into the lib directory.
  2. managed dependencies are configured in the build definition and downloaded automatically from repositories.

How do I get all built in modules in Python? ›

The best command to show all the installed modules is help('modules'). It gives you name of all the installed modules in python without missing anything. Incase you need names of inbuilt modules only, create a temporary fresh venev and give the command there.

What are the basic Python packages to install? ›

Top 10 Python Packages Every Developer Should Learn
  • #1 NumPy. You can do basic mathematical operations without any special Python packages. ...
  • #2 Pendulum. ...
  • #3 Python Imaging Library. ...
  • #4 MoviePy. ...
  • #5 Requests. ...
  • #7 PyQt. ...
  • #9 Pywin32. ...
  • #10 Pytest.
Mar 23, 2021

How do I add dependencies after creating a project? ›

To assign dependencies to projects
  1. In Solution Explorer, select a project.
  2. On the Project menu, choose Project Dependencies. ...
  3. On the Dependencies tab, select a project from the Project drop-down menu.
  4. In the Depends on field, select the check box of any other project that must build before this project does.
May 16, 2022

What are dependencies of an application? ›

What are Application Dependencies? Application Dependencies occur when technology components, applications, and servers rely on one another to provide a business solution or service. When developers build solutions, they do so with a certain technology stack in mind.

What are the best practices for Python package versioning? ›

Best Practice: Avoid Other Versioning Features

Avoid using other Python versioning features like: Post Releases: Used to address minor errors in a final release. Developmental Releases: Separate from Pre-releases and generally discouraged. Local version identifiers: Used to patch any release (including Post-release).

Is dependency injection Good in Python? ›

A dependency injection framework can significantly improve the flexibility of a language with static typing. Implementation of a dependency injection framework for a language with static typing is not something that one can do quickly.

Should I use virtualenv or Pipenv? ›

If you are working with your personal projects and not installing pipenv, I recommend installing pyenv-virtualenv. If you are working in a team or with more than one system, I recommend you to install pipenv which I am covering next.

What are the 4 data structures in Python? ›

The basic Python data structures in Python include list, set, tuples, and dictionary. Each of the data structures is unique in its own way.

What are the 4 built in data structures in Python? ›

Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set.

What is the difference between versioning and version control? ›

Version management is a method of tracking changes to a file or set of files over time. Because each archived version is stored with a time stamp and a user ID, it is always possible to revert to a previous version at a later date. Version control is used in software development to keep track of source code.

What are two approaches to version control? ›

There are two types of version control: centralized and distributed.

How do you maintain versioning? ›

Five Tips for Implementing Semantic Versioning
  1. 1 - Communicate clearly to your users. ...
  2. 2 - Have an open release schedule (that changes gradually) ...
  3. 3 - Be consistent and predictable. ...
  4. 4 - Communicate changes regularly and transparently. ...
  5. 5 - Get user feedback.
Jan 24, 2018

Why we should not use dependency injection? ›

Basically, dependency injection makes some (usually but not always valid) assumptions about the nature of your objects. If those are wrong, DI may not be the best solution: First, most basically, DI assumes that tight coupling of object implementations is ALWAYS bad.

How much RAM is needed to run Python? ›

RAM. Any laptop for Python Programming should have at least 8 GB of RAM. But I recommend getting at least 16 GB of RAM if you can afford it. Because, the bigger the RAM, the faster the operations.

Which dependency injection method is better? ›

Setter Injection is the preferred choice when a number of dependencies to be injected is a lot more than normal, if some of those arguments are optional than using a Builder design pattern is also a good option. In Summary, both Setter Injection and Constructor Injection have their own advantages and disadvantages.

What is the best virtual environment for Python? ›

Two most popular virtual environment libraries for Python are venv and virtualenv. The difference between these two are negligible. However, there is one big difference and that is venv is a standard library that does not need to be installed while virtualenv needs to be installed with pip.

Do people still use pipenv? ›

Many people stopped using pipenv when they believed the project to have been abandoned in 2019. However, it turns out pipenv is still under active development. As of writing the most recent release was v2020. 11.15.

Do people still use virtualenv? ›

Virtual Environment

It is still used by many although people are moving to improved pipenv or conda (explained below). There you go! thats how you create a new environment. pip install package to install any package you need.

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 6487

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.