PythonPython Environment and Development ToolsPython package management
What is a `requirements.txt` file?
Question 23 of 24 · Updated
On this page
- 1. What does a requirements.txt file contain?
- 2. Understanding version specifiers
- 3. How does pip use the requirements file?
- 4. Create and use a requirements file
- 5. Practical offline example: requirements and constraints
- 6. Requirements files vs constraints files
- 7. Environment markers, extras and file inclusion
- 8. How do you generate requirements.txt?
- 9. requirements.txt vs pyproject.toml vs a lockfile
- 10. Reproducible and secure installation
- 11. Common mistakes and troubleshooting
- ModuleNotFoundError after installing requirements
- Requirements cannot be resolved
- A requirements file includes packages unrelated to the project
- The installation works on one machine but fails on another
- Secrets are present in the requirements file
- Requirements are mistaken for a vulnerability scan
- 12. Best practices
- Interview-ready answer
- Official references
A requirements.txt file is a plain-text file that lists Python distribution requirements for pip to install. It helps developers share an application's dependency specification and recreate an environment on another machine.
For example, instead of asking each developer to install every library manually, a project can keep a reviewed requirements file in version control. A developer can then install its requirements into a virtual environment with:
BASHpython -m pip install -r requirements.txt
The filename requirements.txt is conventional, not mandatory. pip can read a requirements file with another name when supplied through the -r option. The file is input to pip, not Python source code, and is not automatically executed or installed merely because it exists in a repository.
1. What does a requirements.txt file contain?#
A requirements file can contain package names, version specifiers, environment markers, comments and certain pip options.
For illustration:
# Application dependencies
requests>=2.32,<3
pytest>=8,<9The first requirement accepts requests releases satisfying both comparisons. The second accepts pytest releases from version 8 up to, but not including, version 9. These are example constraints, not recommendations about current package versions or security.
A requirements file can also contain exact version pins:
requests==2.32.3That requirement requests the specified version, subject to availability and compatibility. An exact pin is not automatically a security recommendation or a guarantee of artifact integrity.
The appropriate specification depends on whether the project is an application, a reusable library or a development-only environment.
2. Understanding version specifiers#
Python packaging defines standard version comparison syntax. The most common specifiers are:
| Specifier | Meaning | Example |
|---|---|---|
| No specifier | No explicit version restriction | requests |
| == | Match a specified version | requests==2.32.3 |
| >= | At least a given version | requests>=2.32 |
| <= | At most a given version | requests<=2.32.3 |
| < | Below a given version | requests<3 |
| > | Above a given version | requests>2.31 |
| != | Exclude a version | requests!=2.32.1 |
| ~= | Compatible-release clause | requests~=2.32.0 |
Comma-separated specifiers are combined as conditions that must all hold. For example, requests>=2.32,<3 specifies both a lower bound and an upper bound.
The compatible-release clause is more specific than simply allowing any future release. For example, ~=2.32.0 corresponds to >=2.32.0 and ==2.32.* under the standard version-specifier rules. The number of version components affects its upper range.
Version matching follows the Python packaging specification, including its rules for pre-releases and local versions. Do not compare version strings alphabetically in a custom dependency-management implementation.
3. How does pip use the requirements file?#
The -r option instructs pip to read requirements from the supplied file.
requirements.txt
|
v
pip reads requirements and options
|
v
Evaluate applicable environment markers
|
v
Resolve compatible distribution candidates and dependencies
|
v
Install selected artifacts into the chosen Python environmentA requirements file may list only the application's direct dependencies. pip reads their distribution metadata and resolves additional transitive dependencies as needed.
For example, if distribution A requires distribution B, installing A may install B even when B is not explicitly named in the file.
If requirements conflict or suitable artifacts cannot be obtained, resolution or installation can fail. The file does not override platform compatibility, Python version compatibility or package-source availability.
4. Create and use a requirements file#
A team can write the file manually based on reviewed project dependencies or generate a version snapshot from a clean environment.
For a new project, create a virtual environment first:
BASHpython -m venv .venv
On macOS or Linux, use the environment's executable directly:
BASH.venv/bin/python -m pip install -r requirements.txt
On Windows PowerShell, the corresponding command is:
POWERSHELL.\.venv\Scripts\python.exe -m pip install -r requirements.txt
Activation is optional when invoking the environment executable directly. If you activate it, python -m pip will normally select that environment's pip.
Use a trusted package source and verify the chosen interpreter. Avoid routinely installing dependencies into operating-system-managed Python.
5. Practical offline example: requirements and constraints#
Consider two instructional distributions named lesson-demo and lesson-helper. They are synthetic test fixtures, not public packages that you should search for on PyPI.
In the local test, lesson-demo version 1.0 declares lesson-helper>=1,<3. The local wheelhouse contains versions 1.0 and 2.0 of lesson-helper.
wheels/
lesson_demo-1.0-py3-none-any.whl
lesson_helper-1.0-py3-none-any.whl
lesson_helper-2.0-py3-none-any.whlSuppose the approved wheel artifacts have already been prepared. Create the following requirements.txt file:
# Direct application requirement
lesson-demo==1.0
lesson-helper==1.0 ; python_version < "3.0"The second requirement is intentionally conditional for this demonstration. It does not apply to a Python 3 environment. Real projects use environment markers to express genuine version or platform requirements.
Create constraints.txt:
lesson-helper==1.0Run the following in a new environment, from the directory containing the files and wheelhouse:
BASH.venv/bin/python -m pip install --no-index --find-links wheels -r requirements.txt -c constraints.txt
Selected output from the Python 3.13.5 local test:
Ignoring lesson-helper: markers 'python_version < "3.0"' don't match your environment
Successfully installed lesson-demo-1.0 lesson-helper-1.0Although the conditional requirement is ignored, lesson-demo still requires lesson-helper through its metadata. The constraints file restricts that dependency to version 1.0.
Verify the installed distribution versions:
BASH.venv/bin/python -c 'from importlib.metadata import version; print(version("lesson-demo"), version("lesson-helper"))'
Output:
1.0 1.0Check the environment's installed dependency consistency:
BASH.venv/bin/python -m pip check
Output:
No broken requirements found.This example illustrates the distinction between requirements and constraints, transitive dependencies and environment markers. It was executed without network access using locally created pure-Python wheels.
The wheel artifacts are prerequisites for reproducing the exact fixture example. Without them, pip cannot install these synthetic distribution names from the local directory.
6. Requirements files vs constraints files#
A requirements file identifies things that pip should install. A constraints file restricts versions of distributions that are requested directly or indirectly; naming a distribution only in a constraints file does not itself request its installation.
| Feature | Requirements file | Constraints file |
|---|---|---|
| Typical option | -r | -c |
| Requests installation | Yes, for applicable requirements | No, by itself |
| Can restrict versions | Yes | Yes |
| Common purpose | Specify application or development requirements | Apply shared limits to selected dependencies |
For example, a platform team might maintain approved version constraints across several services, while each service declares its own application requirements.
A constraints file cannot make an incompatible dependency set valid. If the application requires a version excluded by the constraint, pip may report a resolution failure.
7. Environment markers, extras and file inclusion#
Requirements can express conditions using standard environment-marker syntax. For example:
colorama ; sys_platform == "win32"This requirement applies when the evaluated platform marker is win32. It does not mean that colorama can only run on Windows; the marker expresses this project's installation choice.
Extras request optional dependency groups declared by a distribution. A typical syntax is:
package-name[extra-name]Here package-name and extra-name are placeholders. Use the actual names and supported extras documented by the distribution.
A requirements file can include another requirements file:
-r requirements.txt
pytest>=8,<9This might be the contents of requirements-dev.txt, extending the main application's requirements with a development tool. Avoid circular includes, and keep included files and their paths consistent with the repository layout.
The pip requirements-file format also supports certain options, such as constraints and source configuration. It is a pip-specific input format and is not limited to the standard requirement-string grammar.
8. How do you generate requirements.txt?#
After preparing a clean virtual environment, pip freeze can record installed distributions in requirements-style format.
BASH.venv/bin/python -m pip freeze > requirements.txt
This command replaces the destination file through shell redirection. If an existing requirements.txt contains carefully maintained direct requirements, comments or options, do not overwrite it unintentionally. Write the snapshot to a separate file for review instead:
BASH.venv/bin/python -m pip freeze > frozen.txt
For the locally tested fixture environment, the output was:
lesson-demo==1.0
lesson-helper==1.0The snapshot includes the installed application distribution and its dependency. It does not identify which one was originally requested directly.
By default pip freeze excludes certain bootstrap packaging tools, with the exact exclusions depending on the Python version. The --all option includes them. Consult the installed pip version's help when a complete inventory is required.
Do not generate a project dependency file from a global environment containing unrelated packages. Doing so may add unnecessary dependencies and obscure the project's actual requirements.
9. requirements.txt vs pyproject.toml vs a lockfile#
These artifacts solve related but distinct problems.
| Artifact | Typical role |
|---|---|
| requirements.txt | pip installation input, which may contain direct requirements or a pinned resolved set |
| constraints.txt | Restrict versions of packages selected for installation |
| pyproject.toml | Standard project metadata, build-system configuration and tool-specific settings |
| Lockfile | Records resolved dependency information according to the chosen format and tooling |
For reusable Python distributions, dependency metadata is commonly declared in the project's pyproject.toml configuration. That metadata allows consumers to install the distribution and have its dependencies resolved.
For deployed applications, teams often want tighter control over the exact resolved versions and artifacts used by CI and production.
A requirements file can be used as a pinned installation specification, but its filename alone does not make it a lockfile. A file containing unbounded names or broad ranges may resolve differently over time.
10. Reproducible and secure installation#
Exact pins reduce version drift but do not uniquely identify a distribution artifact. Different platforms may use different wheels for the same version, and a compatible artifact may cease to be available.
pip supports hash-checking mode for verifying selected artifacts:
BASHpython -m pip install --require-hashes -r hashed-requirements.txt
A hash-enabled file uses syntax such as:
lesson-demo==1.0 --hash=sha256:REPLACE_WITH_VERIFIED_WHEEL_HASH
lesson-helper==1.0 --hash=sha256:REPLACE_WITH_VERIFIED_WHEEL_HASHThe hash strings above are explicitly placeholders, not valid hashes. Replace them with the SHA-256 digests of the approved artifacts obtained through a trusted process. pip hash can calculate hashes of local distribution files.
In hash-checking mode, pip requires appropriately pinned and hashed requirements, including transitive dependencies. If a requirement permits several approved artifacts, record the corresponding acceptable hashes.
In the local test, a second fresh environment successfully installed both synthetic wheels with --require-hashes and no package index. Its pip freeze output matched the first environment.
Hashes help detect artifact changes relative to trusted expected digests. They do not prove that an artifact is safe, reputable or free of vulnerabilities.
Reproducibility can also depend on Python version, operating system, architecture, build tools, native libraries, package index configuration and installer behaviour. Record these inputs when they matter to the application.
11. Common mistakes and troubleshooting#
ModuleNotFoundError after installing requirements#
Check that the application and pip use the same interpreter. Also verify that the import name matches the installed distribution's documented interface.
Requirements cannot be resolved#
Read the conflicting dependency constraints. Adjust the reviewed dependency specification or select compatible versions. Avoid ignoring requirements merely to force a successful installation.
A requirements file includes packages unrelated to the project#
This often happens when pip freeze is run in a shared or global environment. Recreate a clean environment, install the intended dependencies and review the resulting snapshot.
The installation works on one machine but fails on another#
Check supported Python versions, platform-specific wheels, native dependencies, environment markers and package sources. A pinned version that works on Linux may lack a compatible artifact for a different platform.
Secrets are present in the requirements file#
Do not store package-index passwords or access tokens in version-controlled requirement URLs. Use approved credential configuration and rotate any exposed credentials.
Requirements are mistaken for a vulnerability scan#
A dependency specification describes installation inputs. It must still be maintained and reviewed for compatibility, security and licensing as appropriate.
12. Best practices#
- Commit reviewed dependency specifications and relevant project configuration.
- Create isolated environments before installing dependencies.
- Distinguish direct dependencies from generated environment snapshots.
- Use compatible version constraints or reviewed pins appropriate to the project's release workflow.
- Test installation in a fresh environment and run pip check and application tests.
- Use approved package sources and verified hashes where required.
- Keep development-only tools separate when they are not needed in production.
Interview-ready answer#
A requirements.txt file is a plain-text input file used by pip to describe Python distribution requirements. It can list package names, version specifiers, environment markers and supported pip options. Developers install its requirements using python -m pip install -r requirements.txt, preferably in an isolated environment. A file may be maintained manually or generated as an installed-package snapshot with pip freeze. It improves repeatability but is not automatically a complete lockfile; exact versions, compatible artifacts, hashes and the runtime environment may also need to be controlled.
Official references#
- pip documentation — Requirements File Format
- pip documentation — pip install
- pip documentation — pip freeze
- pip documentation — Secure installs
- Python Packaging User Guide — Version specifiers
- Python Packaging User Guide — Dependency specifiers
- Python Packaging User Guide — pyproject.toml specification
Verification note: Local tests used Python 3.13.5 and pip 25.1.1 on Linux. Two clean virtual environments were created; synthetic wheel installation, marker evaluation, constraints, version inspection, pip check, pip freeze and hash-verified reinstallation passed. Public package downloads and Windows-specific commands were not executed. Reference links are supplied from established knowledge under the authorised offline research exception; live documentation was not checked.
References
- 1.pip documentation — Requirements File Formatpip.pypa.io
- 2.pip documentation — pip installpip.pypa.io
- 3.pip documentation — pip freezepip.pypa.io
- 4.pip documentation — Secure installspip.pypa.io
- 5.Python Packaging User Guide — Version specifierspackaging.python.org
- 6.Python Packaging User Guide — Dependency specifierspackaging.python.org
- 7.Python Packaging User Guide — pyproject.toml specificationpackaging.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design