From the free course pandas documentation on Lykke
API Reference and Contribution Guide
Key concepts: Public vs. Private API · Contribution Workflow · Development Environment Setup · Code and Documentation Standards · Software Versioning · Release Notes
For advanced users and developers, this section covers the complete public API, the project's development lifecycle, and how to contribute to the pandas library. It also includes information on release notes to track the library's evolution.
API Reference and Contribution Guide
Transitioning from a proficient user of a library to a contributor or a power user who can build robust, long-lasting applications requires a deeper understanding of the project's structure, its development philosophy, and its public-facing contract. This guide serves as the bridge, providing a definitive overview of the library's Application Programming Interface (API), the complete workflow for contributing code and documentation, and the standards that ensure the project's quality and longevity. Mastering this material is essential for anyone looking to write mission-critical code that depends on this library or to participate directly in its evolution.
AI_SVGI_SVG## The API: A Contract with the User
At its core, a library's API is a formal contract. It defines the stable, predictable ways a user can interact with the software. However, not all functions, classes, and modules you can import are part of this contract. Understanding the distinction between the public and private API is the single most important concept for building reliable software that won't break when the library is updated.
Public vs. Private API
Public API: The set of classes, methods, functions, and parameters that the library developers have committed to supporting. The public API is stable; it will only change in predictable ways, typically with ample warning (deprecation periods) and clear documentation in release notes. Changes that break backward compatibility are reserved for major version releases.
Private API: The internal implementation details of the library. These are the functions, modules, and objects the library uses to do its work. They are not intended for external use and can be changed, renamed, or removed at any time, even in a minor patch release, without any warning.
Why This Distinction Matters
The separation of public and private APIs is fundamental to software engineering. It allows library developers the freedom to refactor, optimize, and improve the internal codebase without the fear of breaking user applications. For the user, it provides a stable foundation to build upon. Relying on the public API ensures that your code will continue to work across future versions of thelibrary (excluding major, breaking changes). Conversely, building an application that depends on private, internal components is brittle and almost guaranteed to fail unexpectedly during a routine dependency upgrade.
Identifying Public vs. Private APIs in Practice
In the Python ecosystem, and specifically within libraries like pandas, several conventions signal the status of an API component:
| Convention | Example | Status | Description |
|---|---|---|---|
| No Underscore Prefix | pandas.read_csv() |
Public | The primary, documented way to access functionality. |
| Single Underscore Prefix | _internal_method() |
Private | A strong convention indicating the method is for internal use only. |
| Dunder Methods | __len__() |
Public Protocol | Part of a public protocol (e.g., the container protocol), but should be used via public functions like len(df) rather than direct calls. |
| Underscore-Prefixed Modules | pandas.io.formats._css |
Private | The entire module is considered internal and subject to change. |
| Explicit Documentation | "This function is for internal use." | Private | The documentation will explicitly state the component is not part of the public API. |
Concrete Example: The Wrong and Right Way
Imagine you want to get the internal array manager for a pandas DataFrame. You might discover an internal attribute that seems to do the trick.
import pandas as pd
import numpy as np
# Create a sample DataFrame
df = pd.DataFrame(np.random.rand(3, 2), columns=['A', 'B'])
# --------------------------------------------------------------------
# INCORRECT: Relying on a private API
# The `_mgr` attribute is an internal implementation detail.
# This code could break in any future pandas release without warning.
# --------------------------------------------------------------------
try:
# This is brittle and not guaranteed to exist or have the same structure
internal_manager = df._mgr
print(f"Accessed private attribute `_mgr`: {type(internal_manager)}")
except AttributeError:
print("`_mgr` attribute does not exist in this version.")
# --------------------------------------------------------------------
# CORRECT: Using the public API
# The `.values` attribute and `.to_numpy()` method are documented,
# public ways to get a NumPy representation of the DataFrame's data.
# --------------------------------------------------------------------
numpy_array_values = df.values
numpy_array_method = df.to_numpy()
print(f"\nAccessed public attribute `.values`: {type(numpy_array_values)}")
print(f"Accessed public method `.to_numpy()`: {type(numpy_array_method)}")
The first approach is a ticking time bomb. The second approach is robust and guaranteed to work according to the library's versioning policy.
The Contribution Workflow: From Idea to Integration
Contributing to a large open-source project follows a structured, collaborative process designed to maintain code quality, ensure consistency, and incorporate changes smoothly. This workflow, largely managed through Git and platforms like GitHub, can be broken down into a sequence of distinct steps.
Step 1: Finding and Claiming an Issue
All work begins at the project's issue tracker. This is the central hub for bug reports, feature requests, and discussions about potential changes.
- For new contributors: Look for issues tagged with labels like
good first issueorhelp wanted. These are specifically curated to be accessible to newcomers. - Claiming an issue: Before you start writing code, leave a comment on the issue thread expressing your intent to work on it. This prevents duplicated effort and allows maintainers to provide early guidance.
Step 2: Forking, Branching, and Syncing
The project's main repository is not modified directly. Instead, contributors work on their own copy (a fork) and submit changes via a Pull Request.
Fork: A personal copy of a repository on your own GitHub account. Branch: An independent line of development within your fork. You should create a new, descriptively named branch for every issue you work on (e.g.,
fix/issue-12345orfeature/new-plotting-backend).
This model isolates your work, preventing your main branch from diverging from the original project's main branch. It's crucial to keep your fork's main branch synchronized with the original (often called upstream) repository.
Here is a typical command-line workflow for setting up your local environment and starting work on a new fix:
# 1. Clone your personal fork of the repository (replace with your username)
git clone git@github.com:your-username/pandas.git
cd pandas
# 2. Add the original repository as a remote named "upstream"
git remote add upstream https://github.com/pandas-dev/pandas.git
# 3. Fetch the latest changes from the upstream repository
git fetch upstream
# 4. Ensure your local main branch is up-to-date with the upstream main
git checkout main
git rebase upstream/main
# 5. Create a new branch for your work, based on the latest upstream main
# Replace '12345-fix-datetime-parsing' with a descriptive name for your issue
git checkout -b 12345-fix-datetime-parsing upstream/main
# Now you are ready to start making changes on your new branch.
echo "Development environment ready on branch: $(git rev-parse --abbrev-ref HEAD)"
Step 3: The Development Loop: Code, Test, Document
A contribution is more than just code. It is a triad of implementation, validation, and explanation.
- Code: Implement the fix or feature. Adhere to the project's coding standards.
- Test: Write new tests that prove your code works correctly. For a bug fix, the ideal test is a regression test—one that fails before your change and passes after. This ensures the bug never reappears.
- Document: Update the documentation. If you've added a new function, it needs a complete docstring. If you've changed behavior, the relevant parts of the user guide or API reference must be updated.
Step 4: Submitting a Pull Request (PR)
Once your changes are complete and tested locally, you push your branch to your fork on GitHub and open a Pull Request. The PR is a formal proposal to merge your changes into the main project repository.
A high-quality PR description includes:
- A link to the issue it resolves (e.g., "Closes #12345").
- A clear explanation of what was changed and why.
- A summary of the approach taken.
- Confirmation that tests and documentation have been added.
Upon submission, automated checks (Continuous Integration, or CI) will run, testing your code on different operating systems and Python versions. All checks must pass.
Step 5: Code Review and Merging
After the PR is submitted, project maintainers and other community members will review your code. They may suggest improvements, ask for clarifications, or request changes. This is a collaborative process. Respond to feedback by pushing new commits to your branch; the PR will update automatically.
Once the reviewers are satisfied and all CI checks are green, a core maintainer will merge your Pull Request. Your contribution is now a part of the project!
Setting Up a Robust Development Environment
To effectively contribute, you must be able to build and test the library from source on your local machine.
Core Dependencies and Environment Management
A dedicated development environment is critical to avoid conflicts with other projects or your system's Python installation. Tools like conda or venv are standard.
| Tool | Purpose |
|---|---|
| Git | Version control system for managing code changes. |
| Python | The specific version(s) the project supports (e.g., Python 3.9+). |
| C/C++ Compiler | Required for building compiled extensions (e.g., Cython .pyx files). |
| Conda / venv | For creating isolated Python environments. |
| pip | For installing Python dependencies. |
Here is a shell script demonstrating how to set up a conda environment and install the necessary dependencies from the project's configuration files.
# Create a new conda environment named 'pandas-dev' with a specific Python version
conda create -n pandas-dev python=3.10 --yes
# Activate the newly created environment
conda activate pandas-dev
# Install dependencies using Mamba for speed (a faster conda alternative)
conda install -c conda-forge mamba --yes
# Install build, test, and documentation dependencies from environment files
# The `-c conda-forge` channel is often necessary for scientific packages
mamba install --file environment-dev.yml --file environment-test.yml -c conda-forge --yes
# Now, build the project's C/Cython extensions in-place
# The `-j 4` flag uses 4 parallel jobs to speed up compilation
python setup.py build_ext --inplace -j 4
echo "Build complete. You can now run the test suite."
Running the Test Suite
Before submitting a PR, you must run the test suite locally to catch any regressions. The pytest framework is commonly used.
- Run the full suite:
pytest pandas(This can take a long time). - Run tests for a specific module:
pytest pandas/tests/io/test_parsers.py - Run a specific test:
pytest pandas/tests/io/test_parsers.py -k "test_read_csv_with_quotes"
Upholding Project Standards
Large open-source projects thrive on consistency. Adhering to established standards for code, tests, and documentation makes the codebase more readable, maintainable, and easier for everyone to contribute to.
Code Style and Linting
Projects enforce a consistent code style to ensure readability. This is typically based on PEP 8, the official style guide for Python code. Automated tools called linters check the code for style violations.
| Tool | Purpose |
|---|---|
black |
An opinionated code formatter that automatically reformats code to a consistent style. |
flake8 |
A linter that checks for PEP 8 compliance, logical errors, and code complexity. |
isort |
A tool that automatically sorts imports alphabetically and groups them. |
These tools are often configured in a pyproject.toml file at the root of the repository.
# Example configuration in pyproject.toml for linting tools
[tool.black]
line-length = 88
target-version = ['py38', 'py39', 'py310']
[tool.isort]
profile = "black"
multi_line_output = 3
[tool.flake8]
# Ignore certain errors, e.g., E203 (whitespace before ':') which conflicts with black
ignore = "E203,W503"
max-line-length = 88
max-complexity = 18
Testing Philosophy and Implementation
A comprehensive test suite is the bedrock of a stable library. Every new feature must be accompanied by tests, and every bug fix must include a regression test.
Here is an example of a well-structured pytest regression test for a hypothetical bug where pd.to_datetime incorrectly parses a specific date format when a timezone is provided.
import pandas as pd
import pytest
from pandas.errors import ParserError
# A regression test for a hypothetical issue (e.g., GH#98765)
# Use a pytest marker to categorize the test
@pytest.mark.parametrize(
"date_str, expected_tz",
[
("2023-10-26T12:00:00Z", "UTC"),
("2023-10-26T12:00:00+01:00", "UTC+01:00"),
],
)
def test_to_datetime_iso_format_with_tz(date_str, expected_tz):
"""
Test that to_datetime correctly parses ISO 8601 strings with timezone info.
This is a regression test for GH#98765.
"""
# The action: call the function being tested
result = pd.to_datetime(date_str)
# The validation: check that the output is correct
assert result.year == 2023
assert result.month == 10
assert result.day == 26
assert str(result.tz) == expected_tz
def test_to_datetime_invalid_format_raises():
"""
Test that an invalid format correctly raises a specific error.
"""
# Use pytest.raises to assert that a specific exception is thrown
with pytest.raises(ParserError, match="Unknown string format"):
pd.to_datetime("This is not a date")
Documentation Standards
Clear, comprehensive documentation is as important as the code itself. Docstrings within the code are the source of truth for the API reference. Most scientific Python projects, including pandas, use the numpydoc format.
A complete docstring includes several sections:
| Section | Content |
|---|---|
| Summary | A brief, one-line summary of the object's purpose. |
| Extended Summary | A more detailed explanation of what the object does. |
| Parameters | A description of each parameter, its type, and what it does. |
| Returns | A description of the returned object(s) and their types. |
| See Also | Links to related functions or methods. |
| Examples | One or more runnable examples demonstrating usage. |
Here is an example of a function with a complete numpydoc docstring:
def compute_weighted_average(values, weights):
"""
Compute the weighted average of a sequence of values.
This function calculates the weighted average, where each value is
multiplied by its corresponding weight, summed, and then divided by
the sum of the weights.
Parameters
----------
values : array-like
A sequence of numbers to be averaged.
weights : array-like
A sequence of weights corresponding to each value. Must be the
same length as `values`.
Returns
-------
float
The computed weighted average. Returns NaN if the sum of weights is zero.
See Also
--------
numpy.average : A more feature-rich version of a weighted average.
Examples
--------
>>> values = [10, 20, 30]
>>> weights = [1, 2, 1]
>>> compute_weighted_average(values, weights)
20.0
"""
import numpy as np
values = np.asarray(values)
weights = np.asarray(weights)
if values.shape != weights.shape:
raise ValueError("`values` and `weights` must have the same shape.")
sum_of_weights = np.sum(weights)
if sum_of_weights == 0:
return np.nan
return np.sum(values * weights) / sum_of_weights
Software Versioning and Release Cycle
Understanding how the software is versioned and released helps you manage dependencies and anticipate changes.
Semantic Versioning (SemVer)
Most open-source projects follow a versioning scheme called Semantic Versioning (SemVer). A version number is expressed as MAJOR.MINOR.PATCH.
Semantic Versioning (SemVer): Given a version number
MAJOR.MINOR.PATCH, increment the:
MAJORversion when you make incompatible API changes.MINORversion when you add functionality in a backward-compatible manner.PATCHversion when you make backward-compatible bug fixes.
This scheme provides clear expectations:
- Updating from
2.1.4to2.1.5(a patch release) should be safe; it only contains bug fixes. - Updating from
2.1.4to2.2.0(a minor release) adds new features but should not break your existing code. - Updating from
2.1.4to3.0.0(a major release) is a significant change that will likely require you to modify your code to adapt to breaking API changes.
The Deprecation Cycle
To avoid abrupt changes in major releases, libraries use a deprecation cycle. When a feature is scheduled for removal, it is first marked as deprecated.
- Warning: Using the feature will raise a
FutureWarningorDeprecationWarning, advising users to switch to a new alternative. - Grace Period: The feature remains functional for one or more minor releases, giving users time to update their code.
- Removal: In a future major release, the deprecated feature is removed entirely.
Understanding Release Notes
The Release Notes (or changelog) are the human-readable summary of all changes in a new version. They are an essential resource for anyone upgrading the library.
Structure and Content
Release notes are typically organized into categories to make them easy to parse:
- Enhancements: New features and additions.
- Bug Fixes: A list of bugs that were fixed, often with links to the original issue reports.
- API Changes: A critical section detailing any changes to the public API, including breaking changes.
- Deprecations: A list of all functions, methods, or parameters that are now deprecated.
- Performance Improvements: Notes on any significant optimizations.
Here is an example of what a release note entry might look like:
### Enhancements
* **New `DataFrame.explode()` method for list-like columns**
The new `DataFrame.explode()` method transforms each element of a list-like to a row, replicating the index values. This is useful for un-nesting data. (GH#12345)
**Old way:**
```python
# Manual, more complex logic
New way:
df = pd.DataFrame({'A': [[1, 2], [3]], 'B': [1, 2]})
df.explode('A')
Reading the release notes *before* upgrading is a best practice. Pay special attention to the "API Changes" and "Deprecations" sections to understand what, if anything, in your code needs to be updated.
Source Materials
Study pandas documentation on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of pandas documentation · Browse more course pages