README.md

xpd

Run uvx xpd check . to find the lines of your Python code that are slow or give a wrong result, and add --fix to let xpd rewrite the ones it can. xpd checks code that uses pandas, NumPy, SciPy, scikit-learn, scikit-lego, MAPIE, Category Encoders, linearmodels, arch, pymoo, plotly or Apache Hamilton. It starts no Python, so a coding agent can run it after every edit.

console
1$ uvx xpd check samples/bad.py
2samples/bad.py:5:15: warning [pandas/row-loop] iterrows() builds a Series for every row. Compute on whole columns instead, such as df["a"] * df["w"]. When each row has to become a Python object, loop over itertuples() or to_dict("records").
3samples/bad.py:6:5: error [pandas/chained-assignment] Chained assignment writes to a copy under copy-on-write, so the frame keeps its old values. Assign to df.loc[i, "a"] instead.
4samples/bad.py:7:1: info [pandas/no-inplace] inplace=True gives no speedup and blocks chaining. Reassign instead.
5samples/bad.py:8:5: warning [pandas/merge-without-validate] merge without validate= can silently duplicate rows.
6samples/bad.py:11:5: warning [pandas/concat-in-loop] out grows by one concat per pass, and each concat copies every earlier row. Collect the frames in a list and concat once after the loop.
7xpd: 5 issues, 2 more with --fix --unsafe-fixes

What a fix changes

xpd check samples/bad.py --fix --unsafe-fixes rewrites two of the five lines and reports the other three again.

diff
1 import pandas as pd
2
3 df = pd.DataFrame({"a": [1, 2], "k": [1, 2]})
4 other = df.copy()
5 for i, row in df.iterrows():
6- df["a"][i] = row["a"] * 2
7-df.dropna(inplace=True)
8+ df.loc[i, "a"] = row["a"] * 2
9+df = df.dropna()
10 m = pd.merge(df, other, on="k")
11 out = pd.DataFrame()
12 for f in ["x.csv"]:
13 out = pd.concat([out, pd.read_csv(f)])

Fix every error, and fix a warning unless you can say why the code is right in that place.

WordMeaning
errorThe code gives a wrong result or raises.
warningThe code is slow or easy to get wrong.
infoA shorter or newer form exists.
safe fixThe rewrite keeps what the code does, and --fix writes it.
unsafe fixThe rewrite may change what the code does. --fix --unsafe-fixes writes it, so read the diff afterwards.

xpd check exits with 0 when it finds no error, with 1 when it finds one, and with 2 when it can't run.

Install

uv tool install xpd installs the xpd command, and uvx xpd check . runs it once without an install.

sh
1uv tool install xpd

Rules

Each library has one pack of rules, and the pack runs only on a file that imports the library. The Python pack runs on every file. The plotly pack also runs on a file that makes plotly the plotting backend of pandas.

PackOne of its rulesWhat the rule reports
pandaschained-assignmentdf["a"][i] = v writes to a copy, so the frame keeps its old values
NumPyappend-flattensnp.append without axis flattens both arrays
SciPyremoved-keywordtol= on the sparse iterative solvers was removed and raises TypeError
scikit-learnfit-on-testA fit on the test rows scored 0.997 AUC on data with no signal
scikit-legothresholder-scoreThresholder.score ignores threshold, so a grid search over 0.1, 0.5 and 0.9 gave 0.875 three times
MAPIEcalibrate-on-training-rowsconformalize on the training rows covered 0.483 of the test rows where 0.9 was asked
Category Encodersordinal-mapping-pairsAn OrdinalEncoder mapping given as a list of pairs codes every row as -1.0
linearmodelsclustered-without-clusterscov_type="clustered" without clusters gives the robust standard errors
archunscaled-returnsReturns as decimals stopped the optimizer with code 4 and gave a mean of 4.02 where 0.056 was right
pymooobjectives-stacked-by-rowout["F"] = np.array([f1, f2]) in a Problem gives each solution the wrong values
plotlymarker-size-diameterA marker's size is its diameter, so markers of size 10 and 20 had areas of 78.5 and 314.2 square pixels
Hamiltonnode-mutates-inputA node writes to its input, and Hamilton hands the same object to other nodes
Pythondict-str-anydict[str, Any] in a signature hides the keys the function uses

xpd rules lists every rule, and the rules page shows each one with code before and after.

Commands

xpd <command> -h lists the flags of a command, and the commands page shows the output and the exit codes of each one.

text
1xpd
2├── lint
3│ ├── check [paths] lint files and folders, and rewrite with --fix (alias: scan)
4│ ├── rules list every rule with its documentation
5│ └── hook lint the files that an agent's edit changed
6├── look up a library
7│ ├── find "<task>" find library symbols, rules and worked recipes for a task
8│ ├── api <name> read one symbol, method or recipe in full
9│ └── index <source> build a search index from library source
10├── read and rewrite code
11│ ├── run [paths] find a code pattern, and preview or apply a rewrite (alias: query)
12│ ├── outline [paths] show imports, definitions and members with line numbers
13│ └── graph <files> print the dataflow of step code or Hamilton modules
14├── run the project's Python
15│ ├── profile <data file> print dtypes, nulls, unique counts and memory per column
16│ ├── equiv old.py new.py run two scripts and compare the `result` each one leaves
17│ └── refit <contract> refit a saved Pipeline on raw training rows and compare
18├── write your own rules
19│ ├── new create a rule project, a rule, a test case or a utility
20│ └── test check rule examples and compare snapshots
21└── connect a tool
22 ├── mcp start the MCP server for agents
23 ├── lsp start the language server for editors
24 ├── skill print the agent skill for the installed version
25 └── completions <shell> print shell completion for bash, elvish, fish, powershell or zsh

Only profile, equiv and refit start Python, and they need pandas in the project's environment. Every other command reads files.

Look up a library you don't know

xpd find "<task>" names the classes, the rules and the worked examples for a task in your own words, also for a library you haven't installed. xpd api <name> then prints one of them in full, with each parameter as the source writes it, so you see the type annotation and the default. A stub file writes ... for a default. The name can also be a method of a class, such as Class.method.

console
1$ xpd find "time series bootstrap for cross validation" --limit 1
2Symbols
3sklearn.model_selection.TimeSeriesSplit(n_splits, max_train_size, test_size, gap) [class]
4Time Series cross-validator.
5Rules: sklearn/groups-ignored, sklearn/removed-in-sklearn
6Rules
7sklego/group-time-series-split-folds [rule]
8The rule reports `GroupTimeSeriesSplit` with 6 or more splits. The class tries every combination of
9split points over the groups to find the most even folds, so each extra fold multiplies the time.
10Recipes
11mapie/recipe/generate-a-sampling-method-that-block-bootstraps-the [recipe]
12Generate a sampling method, that block bootstraps the training set.
13
14$ xpd api mapie.subsample.BlockBootstrap
15mapie.subsample.BlockBootstrap(n_resamplings: int = 30, length: Optional[int] = None, n_blocks: Optional[int] = None, overlapping: bool = False, random_state: Optional[Union[int, RandomState]] = None) [class]
16Generate a sampling method, that block bootstraps the training set. It can replace KFold, LeaveOneOut or SubSample as cv argument in the TimeSeriesRegressor class.
17 get_n_splits(args, kargs) Returns the number of splitting iterations in the cross-validator.
18 split(X, args, kargs) Generate indices to split data into training and test sets.
19Rules: mapie/unseeded-resampling
20
21$ xpd api mapie.subsample.BlockBootstrap.split
22mapie.subsample.BlockBootstrap.split(X: NDArray, *args: Any, **kargs: Any) [method]
23Generate indices to split data into training and test sets.
Fact about findValue
Results without --limitUp to 5 symbols, 3 rules and 3 recipes
Flags--kind symbol, --kind rule or --kind recipe selects one kind, and --package selects one library
RankingBy keywords and by meaning, so a task finds an entry whose documentation uses other words
Model for the meaningEmbeddingGemma, which the first find downloads once, 333 MB, to ~/.cache/xpd/models
Without the modelfind says so on stderr and ranks by keywords only
Where recipes come fromLibrary documentation and galleries. xpd keeps an example only when its own rules report nothing in it, and it never runs the example

On macOS the model folder is ~/Library/Caches/xpd/models, and on Windows it is %LOCALAPPDATA%\xpd\models. With XDG_CACHE_HOME set it is $XDG_CACHE_HOME/xpd/models.

Use in an editor

xpd lsp starts a language server, so your editor shows each issue while you type, with a quick fix and the rule's documentation on hover. The language server page has the setup for Neovim, Helix, Zed and VS Code.

Use with a coding agent

Pick the plugin when your client supports it, because it sets up the MCP server and the skills together. Otherwise set up the parts you want one at a time.

WayWhat the agent getsSetup
PluginThe MCP server and the skills togetherLoad this repository in a client that supports Agent Plugins, such as Codex
HookThe issues of each file, right after the editxpd hook in the Claude Code settings
MCP serverTyped tools, the rules, the skills and promptsxpd mcp
SkillsWhen to run each command, and Python style that a linter cannot checknpx skills add bjoernaagaard/xpd

Plugin

Codex installs the plugin with two commands. The plugin starts xpd with uvx, so the machine needs uv.

sh
1codex plugin marketplace add bjoernaagaard/xpd
2codex plugin add xpd@xpd

The repository is a plugin in the Agent Plugins format, version 1.0.0. Version 1.0.0 has no hooks, so you add the hook below yourself.

text
1xpd, loaded as a plugin
2├── plugin.json the name and version of the plugin
3├── skills/ xpd, python-best-practices and python-review
4├── mcp.json starts the MCP server of this version with uvx
5└── .agents/plugins/marketplace.json lists the plugin for Codex

Hook

Add the hook below to .claude/settings.json in your project, and Claude Code shows the agent the issues of each .py file it edits, in the same turn.

json
1{
2 "hooks": {
3 "PostToolUse": [
4 {
5 "matcher": "Edit|Write",
6 "hooks": [{ "type": "command", "command": "xpd hook" }]
7 }
8 ]
9 }
10}
text
1Claude Code edits features.py
2└── the PostToolUse hook runs xpd hook
3 ├── no issues: exit code 0
4 ├── issues: exit code 2, and Claude Code shows them to the agent
5 └── xpd can't run: exit code 1, and Claude Code shows the message to you

MCP server

The command below adds the MCP server to Claude Code, so the agent calls xpd through typed tools and needs no shell.

sh
1claude mcp add xpd -- uvx xpd mcp
text
1xpd mcp
2├── tools
3│ ├── check, fix lint, and write fixes after the user confirms unsafe ones
4│ ├── graph, profile, equiv, refit the commands of the same names
5│ ├── find, api look up a library for a task and read its API
6│ ├── query, rewrite search code, preview replacements and confirm edits
7│ ├── outline read the project's symbols and imports
8│ ├── new, test create rules, and check their examples and snapshots
9│ ├── rules, rule list the rules, and read one with its examples
10│ ├── discovery_gate, contract, gates judge a run from a data file to a saved model
11│ └── show_issues, show_dataflow, show_columns tables and a chart, in hosts that draw them
12├── resources
13│ ├── xpd://rules/{package}/{rule} one rule's documentation
14│ └── skill://<name>/SKILL.md each skill that ships with xpd
15└── prompts
16 └── lint_and_fix, review, refactor_data_logic, add_to_dataflow, build_pipeline

The server takes every rule and every result from the xpd binary, so it matches the installed version. The MCP page covers other clients, the settings and HTTP. The code mode page shows a run from a data file to a saved scikit-learn model, with checks that xpd runs itself.

Skills

The command below installs the three Agent Skills in skills/. The two Python skills work without xpd, and they run xpd when it is installed.

sh
1npx skills add bjoernaagaard/xpd
SkillWhat it does
xpdSays when to run each xpd command. xpd skill prints it for the installed version.
python-best-practicesHolds the rules an agent follows when it writes or changes Python.
python-reviewReviews a file, package or diff, and cites the rule for every finding.

Documentation

The full guide is at https://bjoernaagaard.github.io/xpd/, and its rules page also explains how to write a rule.

License

You may use xpd's own code under the MIT license or the Apache-2.0 license. The table lists what else ships with xpd.

PartLicenseWhere the text is
xpd's own codeMIT or Apache-2.0, as you chooseLICENSE-MIT and LICENSE-APACHE
Recipes, which are examples taken from library documentationThe license of the library, which is MIT, BSD-3-Clause, Apache-2.0 or NCSAlicenses/, one file per library. xpd api <recipe> prints the license name and the source link with the code
option-ext, a dependency shipped unmodifiedMPL-2.0licenses/option-ext-LICENSE.txt, with the complete source in licenses/option-ext-0.2.0-source.tar.gz and at https://crates.io/api/v1/crates/option-ext/0.2.0/download
EmbeddingGemma, the model that find downloadsThe Gemma Terms of Use at https://ai.google.dev/gemma/termsNot shipped with xpd

The licenses/ folder ships in the crate, the sdist and the wheel, and the package metadata lists the combined licenses.