CodeBlanks Logo Icon CodeBlanks

requirements.txt

Learn dependency management with requirements.txt.

requirements.txt

requirements.txt lists the dependencies of a project, one per line. The pip install -r requirements.txt command installs every package in the list. It is used as an alternative to pyproject.toml in production deployments.

requests>=2.28
httpx==0.24

Each line holds a package and an optional version specifier. The pip freeze > requirements.txt command produces this file by freezing the exact versions of installed packages.

Version specifiers

Dependency lines use version specifiers: >= means at least, == means exact, < means less than, ~= means compatible release.

requests>=2.28    # at least 2.28
httpx==0.24      # exactly 0.24
rich<13         # less than 13

In production, locking with == gives predictability. In development, >= is more flexible but may surprise you on major version bumps.

Practice Count the lines in requirements.txt

Assign the following content to a string variable named requirements:

requests>=2.28
httpx==0.24

Then list the lines with deps = [line for line in requirements.strip().split("\n") if line.strip()]. Print the line count with print(len(deps)) and the first line with print(deps[0]).

Starter code

main.py
# assign a two-line dependency list to a string named requirements
# turn the lines into a list, dropping blank lines
# print the line count and the first line

Sample solution

main.py
requirements = "requests>=2.28\nhttpx==0.24\n"

deps = [line for line in requirements.strip().split("\n") if line.strip()]
print(len(deps))
print(deps[0])

Expected output

2
requests>=2.28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does pip freeze > requirements.txt do?

  • Builds a wheel
  • Removes packages
  • Creates a virtual environment
  • Freezes installed versions Correct answer

Explanation: pip freeze writes the exact versions of installed packages to the file.

2 Complete the >= specifier

Question
requests____2.28
Answer
requests>=2.28

Explanation: >= requires at least this version.

3 Match the version specifiers

Term Meaning
>= At least
== Exact
< Less than
~= Compatible

All lessons in Advanced