How to Contribute Code or Algorithms to TheAlgorithms/Python: A Complete Guide
To contribute to TheAlgorithms/Python, fork the repository, create a feature branch, add your algorithm as a Python module with type hints and doctests in the appropriate category folder, run pre-commit hooks and pytest locally, then submit a pull request for automated CI validation.
TheAlgorithms/Python is one of the largest open-source collections of algorithmic implementations, organized by domain into topic-specific directories. Contributing your code requires adherence to strict style guidelines enforced by automated tooling, ensuring every module includes comprehensive documentation and type safety. Whether you are adding a new sorting routine or optimizing an existing graph traversal, following the repository’s architectural conventions guarantees your contribution passes continuous integration and helps learners worldwide.
Step-by-Step Contribution Workflow
1. Fork and Clone the Repository
Begin by clicking Fork on the TheAlgorithms/Python GitHub page to create your own copy. Clone it locally:
git clone https://github.com/<your-username>/Python.git
cd Python
2. Create a Feature Branch
Isolate your changes in a dedicated branch using descriptive, snake_case naming:
git checkout -b add-<algorithm-name>
3. Select the Correct Directory
Locate the top-level folder that matches your algorithm’s domain. The repository uses a flat, category-based structure:
sorts/– Sorting algorithmssearches/– Search algorithmsdata_structures/– Stacks, queues, trees, etc.graphs/– Graph traversal and pathfindingdynamic_programming/– DP solutions
Do not create new top-level folders unless explicitly approved in an issue. If no category fits perfectly, place the file in the most logical existing folder.
4. Implement the Algorithm
Create a new Python file with a descriptive, snake_case name (e.g., quick_sort.py). Your implementation must satisfy the strict quality gates defined in [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md):
- Docstrings: Every public function requires a Google-style or NumPy-style docstring explaining the algorithm, its time/space complexity, and parameters.
- Doctests: Include example usage in the docstring that can be executed by
pytest --doctest-modules. - Type Hints: Annotate all function signatures (parameters and return values) using Python’s
typingmodule. - No Side Effects: Algorithms must be pure functions. Do not use
print(),input(), or file I/O inside the algorithmic logic.
5. Validate Locally with Pre-Commit Hooks
Before committing, run the automated quality checks configured in [.pre-commit-config.yaml](https://github.com/TheAlgorithms/Python/blob/master/.pre-commit-config.yaml):
pip install pre-commit
pre-commit run --all-files
This executes black (formatting), ruff (linting), and other hooks. All checks must pass.
6. Run Type Checking and Tests
Execute the full test suite to ensure type safety and correctness:
ruff check . # Linting
mypy --ignore-missing-imports . # Type checking
pytest -q --doctest-modules # Run doctests and unit tests
If any test fails, revise your code before proceeding.
7. Commit and Push
Stage your changes with a clear, imperative commit message:
git add sorts/quick_sort.py
git commit -m "Add quick_sort implementation with doctests"
git push origin add-quick-sort
8. Open a Pull Request
Navigate to your fork on GitHub and click New Pull Request targeting TheAlgorithms/Python:master. In the description:
- Reference any related issue with
Fixes #<issue-number>. - Briefly describe the algorithm and its complexity.
- Confirm that all pre-commit hooks and pytest passed locally.
9. Automated CI Validation
GitHub Actions will trigger the workflow defined in the repository’s CI configuration, running ruff, mypy, and pytest across multiple Python versions. If checks fail, push additional commits to your branch to resolve them.
10. Merge
Once maintainers approve and all status checks pass, your PR is merged. Your algorithm becomes part of the public collection and is automatically indexed in [DIRECTORY.md](https://github.com/TheAlgorithms/Python/blob/master/DIRECTORY.md).
Code Quality Requirements in Detail
Pre-Commit Hooks
The repository enforces code style through [.pre-commit-config.yaml](https://github.com/TheAlgorithms/Python/blob/master/.pre-commit-config.yaml). Key hooks include:
- black – uncompromising Python code formatter.
- ruff – extremely fast Python linter and code analyzer.
- mypy – static type checker (often run as a separate step).
Running pre-commit run --all-files before pushing prevents CI failures.
Type Hints and Documentation
Every function must use Python 3 type annotations. For example, in sorts/quick_sort.py:
from typing import List
def quick_sort(arr: List[int]) -> List[int]:
...
Docstrings must include a description, complexity analysis, and runnable doctests. The doctests serve as both documentation and regression tests.
Complete Example: Adding a Sorting Algorithm
Below is a fully compliant implementation that could be submitted as sorts/quick_sort.py. It demonstrates the required structure: module-level docstring, type hints, pure function implementation, and comprehensive doctests.
"""
Quick Sort Implementation
-------------------------
A divide-and-conquer sorting algorithm with average time complexity O(n log n)
and worst-case O(n²). This implementation is not in-place and returns a new list.
Reference: https://en.wikipedia.org/wiki/Quicksort
"""
from typing import List
def quick_sort(arr: List[int]) -> List[int]:
"""
Return a new list containing the elements of *arr* sorted in ascending order
using the quick-sort algorithm.
The implementation is recursive and does **not** modify the original list.
Time Complexity: O(n log n) average, O(n²) worst case
Space Complexity: O(n) auxiliary
>>> quick_sort([3, 1, 4, 1, 5, 9, 2, 6])
[1, 1, 2, 3, 4, 5, 6, 9]
>>> quick_sort([])
[]
>>> quick_sort([42])
[42]
>>> quick_sort([-5, -1, -10, 0])
[-10, -5, -1, 0]
"""
if len(arr) <= 1:
return arr[:] # copy to avoid mutating input
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
if __name__ == "__main__":
import doctest
doctest.testmod()
Save this file as sorts/quick_sort.py, run pre-commit run --all-files and pytest -q, then commit and push.
Summary
- Fork and branch the repository before making changes.
- Place algorithms in the correct top‑level category folder (e.g.,
sorts/,searches/) using descriptive, snake_case filenames. - Write pure functions with complete type hints, docstrings, and doctests; avoid I/O side effects.
- Validate locally using
pre-commit run --all-files,ruff,mypy, andpytestbefore opening a PR. - Submit a Pull Request targeting
masterand ensure all GitHub Actions CI checks pass.
Frequently Asked Questions
Do I need to open an issue before submitting a pull request?
No, you do not need to open an issue first for new algorithms or minor fixes. However, if you plan to refactor a large portion of the codebase or introduce a new top‑level category, opening an issue to discuss the change is recommended to avoid wasted effort.
What type hints are required for contributions?
All function parameters and return values must be annotated using Python’s typing module (e.g., def func(arr: list[int]) -> int:). The repository runs mypy --ignore-missing-imports in CI, so any missing or incorrect type annotations will cause the build to fail.
How do I handle algorithms that require external dependencies?
The repository aims to remain dependency‑light, relying primarily on the Python standard library. If your algorithm absolutely requires an external package, you must add it to the project’s dependency configuration and justify its necessity in the pull request description. Most contributions should use only built‑in modules.
Why was my pull request rejected by the CI checks?
Common reasons include failing to run pre-commit run --all-files locally (resulting in black or ruff formatting errors), missing type hints, absent doctests, or algorithms that perform I/O operations like print() or input(). Review the error logs in the GitHub Actions tab, fix the issues locally, and push a new commit to your branch to re‑trigger the checks.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →