6.4 pip and Third-Party Packages
Beyond built-in modules, Python can use third-party modules or third-party packages maintained by the community or companies. Third-party packages let you add features without writing everything from scratch.
pip
pip is Python's common package manager. It installs, upgrades, lists, and uninstalls third-party packages.
pip install requests
pip list
pip install --upgrade requests
pip uninstall requestsIn real projects, developers often use a virtual environment to isolate dependencies so package versions from different projects do not interfere with one another.
Reading an Installed Package
After installation, you import a third-party package the same way you import a built-in module. The difference is that Python can only import it after the package has been installed in the current environment.
python -m pip install requestsimport requests
response = requests.get("https://example.com")
print(response.status_code)This example is only here to show the import flow. Network requests, status codes, and web APIs are separate topics; you do not need to master them in this section.
requirements.txt
When a project depends on third-party packages, it is common to write the package names into requirements.txt:
requestsThen another developer can install the same dependencies with:
pip install -r requirements.txtFor small exercises, running pip install package_name is enough. For real projects, keeping dependencies in a file makes the environment easier to rebuild.
Virtual Environments
A virtual environment keeps packages for one project separate from packages for another project. This avoids the situation where Project A needs one package version but Project B needs a different version.
Common commands look like this:
python -m venv .venv
source .venv/bin/activate
pip install requestsOn Windows, the activation command is different, but the idea is the same: activate the project environment first, then install packages inside it.