# Python packages

> Add pure-Python packages from PyPI to a plugin with wmpy pip or the web editor, read the compatibility verdict, and keep the plugin small with tree shaking.

URL: https://wmkeyboard.pages.dev/plugins/guides/python-packages/
Section: Plugins

A plugin can carry other people's Python code: a package from
[PyPI](https://pypi.org) copied into the plugin folder, beside your own
modules. This is called vendoring. `wmpy pip` does it from the command line,
and the web editor does it from its menu. Both check the package first and
tell you whether it can run in the keyboard.

## What can be vendored

Only pure Python. The keyboard runs plugins in its own small Python
interpreter (see [The Python you get](https://wmkeyboard.pages.dev/plugins/wm-package/#the-python-you-get)),
so a package qualifies when:

- it is plain `.py` files, with no compiled C, Cython or Rust parts
- it imports only modules the keyboard has, the `wm` package, itself, and
  other vendored packages
- it does not reach the file system, the network, threads or other
  processes directly (reading its own [data files](#data-files) is fine)
- its files fit the keyboard's [size limits](#size-limits)

Many PyPI packages are written for full CPython and fail one of these:
`numpy` is compiled code, and `aiosqlite` needs a database on disk. Small,
self-contained packages have the best chance. The check tells you, file by file and line by line, and it asks
the interpreter in your copy of wmpy rather than a fixed list, so its answer
follows the keyboard as its Python grows.

## Add a package

```bash
cd my-plugin
wmpy pip install humanize
wmpy pip install "tabulate>=0.9" "attrs[tests]"
```

For each package, `wmpy pip install`:

1. Looks it up on PyPI and takes the newest release that fits the version you
   asked for. When two packages need different versions of a third, wmpy
   starts choosing again with both needs known, so langsmith's
   `uuid-utils<1.0` holds even when another package asked for uuid-utils
   first. If no release fits both, it names the two that clash.
2. Downloads its pure-Python wheel (`py3-none-any`), or its source archive
   when there is no wheel and nothing in it needs building. A package that
   ships only compiled wheels gets the `.py` files of one of them (a Linux
   build for the keyboard's Python version when there is one), without the compiled parts.
   Many packages fall back to Python for those (PyYAML, MarkupSafe, msgpack,
   multidict), and the analysis checks that they do. A compiled wheel over
   24 MB is mostly compiled code, so it is refused without downloading it.
   So is a package that only installs a program compiled for computers,
   such as `ruff` or `uv`: its Python just starts that program. A few small
   packages that come only compiled, such as orjson and rpds-py, get the
   keyboard's [pure-Python stand-in](#stand-ins-for-compiled-packages)
   instead, with nothing to download.
3. Checks the download against the SHA-256 that PyPI lists.
4. Reads its dependencies and installs those the same way. Markers such as
   `python_version < "3.9"` are read as CPython on Linux (aarch64) would read
   them, at the version `sys.version_info` gives in a plugin (3.13 today),
   and extras only when you ask for them: `attrs[tests]`. `requests` and
   `httpx` are the keyboard's own and come without their dependencies. A
   package that needs one of them and cannot load without something it
   brings on a computer, such as `urllib3`, gets that added. A package of
   type hints, such as `types-requests`, holds nothing to run, so it is not
   installed.
5. Applies the small [patches](#patched-packages) the keyboard keeps for a
   few popular packages, then analyses every package and refuses those that
   will not work.
6. Copies the importable `.py` files to the top of the plugin folder, writes
   the package's [data files](#data-files) into a module beside them, puts
   the licence files in `licenses/<name>/`, and records it all in `wmpy.lock`.

It prints a table of what it did, the problems it found, and how close the
plugin is to the keyboard's limits.

- my-plugin/
  - plugin.json
  - main.py
  - humanize/ the package, as `import humanize` finds it
    - \_\_init\_\_.py
    - number.py
    - time.py
  - six.py a single-module package
  - licenses/
    - humanize/
      - LICENCE
  - wmpy.lock what was installed, from where

Your code then imports it as usual: `import humanize`. The package's tests
are left out, and so is any `.py` file whose path is not a module name.

| Option | Does |
|---|---|
| `--dir FOLDER` | The plugin folder. The default is the folder you are in. |
| `--no-deps` | Installs only the packages you name. |
| `--allow-warnings` | Installs packages whose verdict is `warnings`. |
| `--force` | Installs even `incompatible` packages, and downloads again what is already installed. |
| `--json` | Prints the result as JSON. |

A package never replaces your own files. If the plugin already has a
`helpers.py` and a package brings a `helpers` module, the package is refused.

## The verdicts

Every package gets one of three verdicts, and every problem names its file,
line and column.

- `ok`: nothing found that would stop it.
- `warnings`: it loads, but something may fail or act differently. Usually a
  function that uses what plugins do not have (`open()`, `os`), which only
  fails when that function runs, or Python the keyboard runs differently,
  such as a number too big for 64 bits.
- `incompatible`: it will not load, or the keyboard refuses the plugin. A
  missing module imported at the top of a file, syntax the keyboard's parser
  rejects, compiled code, or a file over the limits.

An import inside `try: ... except ImportError:` or
`with suppress(ImportError):` is noted but does not count, since the package
already copes without it. Code that never runs in a plugin
is not checked at all:

- anything under `if TYPE_CHECKING:` or `if __name__ == "__main__":`;
- a branch for another Python or another system, such as `if PY2:`,
  `if sys.version_info >= (3, 14):`, `if sys.platform == "win32":` or
  `if hasattr(sys, "pypy_version_info"):`. A `hasattr` test on any standard
  module, such as `hasattr(typing, "TypeForm")`, is asked of the keyboard's
  Python itself, and an environment variable is unset, since a plugin's
  `os.environ` starts empty. wmpy also follows such a test
  through a name the package sets, even in another of its modules
  (`from ._compat import WIN`). It follows a switch a package turns off when
  its compiled speedups fail to import, too;
- a branch on whether a package is installed, asked with
  `importlib.util.find_spec("numpy")` or with a small function of the
  package's own, such as `def has_lxml():` around a `try: import lxml`. wmpy
  works out what such a function returns when it only imports, compares and
  returns. If it does anything wmpy cannot foresee, or has a decorator, the
  branch is checked as usual;
- the `except ImportError:` fallback of an import that works, and the `else:`
  of a `try` whose import fails;
- a module only that code imports, a module that needs `winreg` or `msvcrt`
  when it loads, one that needs `ctypes.wintypes` and that nothing in the
  package imports, and a package's `__main__.py`.

Where a module is loaded decides how much its problems count. One imported
only inside functions, or only its tests and command line import, makes only
that code fail: its problems are warnings. One imported only under
`except ImportError:` can fail to import and the package goes on without it.
A public module nothing in the package imports, such as
`urllib3.contrib.pyopenssl`, loads only if your plugin imports it. Its own
problems still count, but a package only it imports, one the package does
not depend on, makes it an add-on for people who have that package: a
warning. So does a desktop's windows or terminal (`tkinter`, `curses`,
`readline`, `pty`), as in `tqdm.tk`, and something of the package's own that
the release came without, as a leftover benchmark may need. A file over the keyboard's limits that nothing loads when the
package loads is a warning too, since `wmpy pack` leaves out what your code
never reaches.

`from .base import *` brings in what `base` defines, and wmpy follows it,
through as many modules as it goes. A module that makes its names as it
runs, writing to `globals()` or replacing itself in `sys.modules`, may have
any name. Packages that share a namespace, such as `google.auth` from
google-auth and `google.cloud.storage` from google-cloud-storage, find each
other's modules when both are installed.

By default `install` takes only `ok` packages. `--allow-warnings` takes
`warnings` too, and `--force` takes anything. A package whose dependency was
refused is refused with it.

## Patched packages

A few popular packages do one thing the keyboard's Python cannot, in one
place. `wmpy pip` and the web editor change that line when they add the
package, as Pyodide does for the packages it ships, and say so:

| Package | Changed | Why |
|---|---|---|
| click | `click/termui.py` | click keeps the `input` builtin as its prompt function when it loads. Prompting raises `EOFError`, as with no terminal. |

A patch that no longer fits a new release is skipped, and wmpy says that too.
The patches live in
[`native/wm-python-pip/patches`](https://github.com/wasi-master/WMKeyboard/tree/main/native/wm-python-pip/patches).

## Stand-ins for compiled packages

A few small packages ship only as compiled Rust, yet popular packages need
them: jsonschema needs rpds-py, and many API clients use orjson. For these
the keyboard keeps a stand-in written in Python, with the same import name
and the same API. When the release `wmpy pip` or the web editor picks has
no pure-Python wheel, the stand-in goes in under that release's version,
and the install says so.

| Package | Imports as | Leaves out |
|---|---|---|
| fastuuid | `fastuuid` | |
| jiter | `jiter` | the string cache: `cache_usage()` is always 0 |
| orjson | `orjson` | numpy arrays |
| rpds-py | `rpds` | |
| uuid-utils | `uuid_utils` | |

On CPython, the rpds-py stand-in passes all of that project's own tests.
orjson's passes 755 of 762 (the numpy and memory tests were left out) and
jiter's 30 of 35. The uuid-utils and fastuuid stand-ins were compared with
the real packages, not run through their test suites. A stand-in is slower than the compiled
package: orjson's `dumps` writes the same bytes, but in Python, not Rust.
For the few kilobytes a plugin sends, that rarely shows. A release that
ships a pure-Python wheel is installed as it is. The stand-ins are the
keyboard's own code, under its MIT licence, and live in
[`native/wm-python-pip/replacements`](https://github.com/wasi-master/WMKeyboard/tree/main/native/wm-python-pip/replacements).

## Data files

Some packages read files they ship beside their modules: jsonschema its
JSON schemas, a spell checker its word list, a template engine its templates.
A plugin holds only Python modules, so `wmpy pip` and the web editor write
those files into a module of the package, `<package>/_wmdata.py`, as text
(or base64 for binary files). In the plugin they read as files again, at the
path the package's `__file__` leads to (`/plugin/<package>/...`):

- `open()` reads them, in text or binary mode;
- `importlib.resources.files(...)`, `read_text`, `open_binary` and `as_file`,
  and `pkgutil.get_data`, find them;
- `os.path.exists`, `isfile`, `isdir`, `os.listdir`, `os.scandir`, `os.walk`,
  `os.stat` and `pathlib` see them.

They are read-only: opening one to write raises `PermissionError`, and so
does any path outside the plugin's packages. A package's data may take
2 MB once written as Python, and one module holds up to 1 MB, so more goes
into `_wmdata_2.py` and on. A package with more data than that, such as
Babel's locale data, gets none, and the install says so. `wmpy pack` keeps
a package's data modules while the plugin uses the package.

An `open()` a package makes when it loads counts as a warning, not an error,
when the package came with data, since it most likely opens one of those
files.

## Check before you install

```bash
wmpy pip check emoji
wmpy pip check ./downloads/tidy-1.0-py3-none-any.whl
wmpy pip check ./my-package-source/
wmpy pip check python-dateutil --json
```

`check` downloads and analyses, writes nothing, and exits with 1 when a
package is incompatible. It takes a PyPI name, a wheel, a source archive, or a
folder of Python files. With `--json` it prints
`{"packages": [{"name", "version", "verdict", "problems": [...]}]}`, where each
problem has `severity`, `code`, `message`, `file`, `line`, `col` and `help`.
[wmpy's MCP server](https://wmkeyboard.pages.dev/plugins/ai-agents/) gives AI agents the same check as
its `pip_check` tool.

Problems carry a short code. The common ones:

| Code | Means |
|---|---|
| `syntax` | The keyboard's parser rejects the file, and says why. |
| `missing-import` | Nothing provides this module. `help` says which package to install when it is not a standard one. |
| `sandbox-import` | A module plugins go without on purpose: `sqlite3`, `dbm`, `pty`. `help` names what to use instead, such as `wm.files`. Many others, such as `socket` and `tempfile`, are there as stand-ins that raise only when used: see [the Python you get](https://wmkeyboard.pages.dev/plugins/wm-package/#the-python-you-get). |
| `missing-attribute` | The keyboard's version of a standard module lacks this, such as `sys.settrace`. A name only Python 2 had, such as `itertools.izip`, is a warning. |
| `missing-builtin`, `sandbox-builtin` | A builtin the keyboard does not have, or one that raises an error in plugins when called: `open` (no file system, apart from the package's [data files](#data-files)), `input` (no terminal). Only naming one, as in `prompt = input`, is fine. |
| `missing-name` | `from x import y` where `x` has no `y`. |
| `c-extension`, `c-source`, `needs-build` | Compiled code, its sources, or a source archive that would have to be built. |
| `file-too-big`, `too-deep`, `module-name` | A file the keyboard refuses: over 1 MB, deeper than `a/b/c/d/e/f/g/h.py`, or a path that is not a module name. An error when the package loads it, a warning when it does not. |
| `multiple-inheritance`, `metaclass`, `big-int` | Python the parser takes but the interpreter runs differently or not at all. |

## Keep track

```bash
wmpy pip list
wmpy pip why six
wmpy pip update
wmpy pip update humanize
wmpy pip update humanize --latest
wmpy pip remove tabulate
wmpy pip verify
wmpy pip sync
```

- `list` shows every vendored package with its version, verdict, size,
  licence and what needs it.
- `why` says why a package is there: you installed it, or another package
  needs it.
- `update` moves packages to their newest releases and analyses them again.
  With a name it updates that package alone. It stays inside what you asked
  for: a package installed as `"python-dateutil>=2.8,<3"` moves to the newest
  2.x. `--latest` takes the newest release anyway, and from then on the lock
  asks for the bare name.
- `remove` takes a package out: its files, its licences and its line in
  `wmpy.lock`. It refuses a package another one needs, unless you add
  `--force`, and tells you when a dependency is no longer needed by anything.
- `verify` checks each vendored file against the SHA-256 the lock keeps of
  it, and exits with 1 when a file is missing or was changed by hand. Run it
  in CI to catch a package edited in place.
- `sync` puts back what `verify` finds, downloading the locked versions
  again; `--all` downloads every package. A lock written by an older wmpy
  keeps no SHA-256s, and `sync` records them when every file is there.

`list`, `why`, `remove`, `verify` and `sync` take `--json`, and `install`
takes `-r requirements.txt` (more than once, too) for the packages a list
names. Options lines in such a list, such as `--index-url`, are refused,
since wmpy installs from PyPI only.

## wmpy.lock

`wmpy.lock` records what each package put in the folder, so `remove`,
`update` and tree shaking know which files are vendored. The web editor reads
and writes the same file.

```json
{
  "version": 1,
  "packages": {
    "humanize": {
      "version": "4.17.0",
      "roots": ["humanize"],
      "files": ["humanize/__init__.py", "humanize/number.py", "licenses/humanize/LICENCE"],
      "requested": "humanize>=4",
      "source": "https://files.pythonhosted.org/packages/.../humanize-4.17.0-py3-none-any.whl",
      "sha256": "02d08995...",
      "hashes": {"humanize/__init__.py": "5b0f2e81...", "humanize/number.py": "c19a7d04..."},
      "license": "MIT",
      "requires": [],
      "verdict": "ok",
      "problems": 0
    }
  }
}
```

Keys are package names in PyPI's normalized form (`python-dateutil`).
`roots` are the top-level modules the package adds, and `requires` the
normalized names of the packages it needs. `requested` is what you typed, for
a package you installed by name, and `update` keeps to it; a package that is
there only because another needs it has none. `sha256` is the wheel's, and
`hashes` each file's, which `verify` checks. `wmpy pack` leaves `wmpy.lock`
out of the `.wmplugin`. Keep it with your plugin's source.

## Licences

Vendoring copies someone else's code into your plugin, so their licence
comes with it. wmpy copies each package's licence files to
`licenses/<name>/`, records the licence name in `wmpy.lock`, and warns when a
package names none. Check that a package's licence lets you share it before
you publish the plugin. The `licenses/` folder goes into the `.wmplugin`
with the code.

## Size limits

The keyboard refuses a plugin over these limits:

| | |
|---|---|
| Files in the `.wmplugin` | 64, `plugin.json` and licence files included |
| All files together | 4 MB |
| One `.py` file | 1 MB |
| Module paths | eight parts at most: `a/b/c/d/e/f/g/h.py` |

Keyboards up to 0.6.8rc1 took 256 KB and four parts (`a/b/c/d.py`), and
refuse a plugin with a larger or deeper file.

Packages add up fast. `install` and `update` count the files after each run
and warn when the plugin is over. `wmpy pack` usually brings it back under,
because it leaves out what the plugin never uses.

## Tree shaking

`wmpy pack` shakes the vendored packages before it writes the `.wmplugin`.
Starting from your entry script and your own modules, it follows every
import, and leaves out the vendored modules nothing reaches. A package you
installed but never import goes entirely. Your own files are never touched.

```bash
wmpy pack                  # leave out unused modules
wmpy pack --shake-symbols  # also unused functions, classes and assignments
wmpy pack --no-shake       # keep every vendored file whole
```

With `--shake-symbols` it also removes, inside the vendored modules that stay,
the top-level definitions nothing uses, and the imports of modules that would
then load for nothing. For a plugin that calls one function of `humanize`,
this cuts its Python from 50 KB to 18 KB. The removed lines are left blank,
so line numbers in error messages still match the package's source.

Shaking only removes what cannot matter. A module keeps everything when it
looks itself up by name (`globals()`, a module `__getattr__`), when it is
star-imported, or when code passes the module around as a value instead of
calling `module.name`. A string that is exactly a name, as in
`getattr(obj, "name")`, counts as a use of that name. Statements that do
something when the module loads, such as a call or a registration, always
stay, with everything they use. `pack` prints a note for each package or
module it kept whole, and why.

## In the web editor

The [plugin editor](https://wmkeyboard.pages.dev/addons/new?type=plugin) can add packages too.

1. In the editor's menu, or under **Files**, press **Add a Python package**.
2. Type the name as `pip` takes it, such as `requests[socks]`, and press **Find**.
3. Pick a version and press **Check**.
4. Read the result for each package, then press **Add** (**Add anyway** when it won't run).

**Check** downloads each package from PyPI in your browser and compares it
with the sha256 PyPI lists. It runs the same check as `wmpy pip`, and shows
the verdict and the lines that won't run before it adds anything. Only
pure-Python wheels work here, and the keyboard's
[stand-ins](#stand-ins-for-compiled-packages) for compiled packages. For a
package that comes only as source, try `wmpy pip install` on a computer.

The editor writes the same files and the same `wmpy.lock` as `wmpy pip`, so a
plugin can move between the web editor and `wmpy` freely. **Remove** keeps
any file another package needs. When it saves the `.wmplugin`, the editor
shakes the packages as `wmpy pack` does, and **Details** says how much it
removed.

## Downloads and the cache

wmpy reads the package list from `pypi.org` and downloads files only from
`files.pythonhosted.org`. It sends nothing about you or your plugin. Each
download is checked against PyPI's SHA-256 and kept in a cache folder, so
installing the same release again needs no network:

| System | Cache folder |
|---|---|
| macOS | `~/Library/Caches/wmpy` |
| Linux | `$XDG_CACHE_HOME/wmpy`, or `~/.cache/wmpy` |
| Windows | `%LOCALAPPDATA%\wmpy\cache` |

Set `WMPY_CACHE_DIR` to use another folder. When PyPI cannot be reached,
wmpy uses the release list it saved last time and says so.
