tywrap
v0.4.0
Published
Generate type-safe TypeScript wrappers for any Python library — Node.js, Deno, Bun, and browsers via Pyodide.
Maintainers
Readme
tywrap
TypeScript wrapper for Python libraries with full type safety.
⚠️ Experimental — APIs may change before v1.0.0. See the releases page for breaking changes.
Features
- Full Type Safety - TypeScript definitions generated from Python source analysis
- Development Hot Reload - Real Node watch sessions regenerate wrappers and swap the active bridge without re-importing generated modules
- Generic-Aware Declarations - Preserves simple
TypeVarand callableParamSpecgenerics in generated.tsand.d.tsoutput - Multi-Runtime - Node.js (subprocess) and browsers (Pyodide)
- Rich Data Types - numpy, pandas, scipy, torch, sklearn, and stdlib types
- Efficient Serialization - Apache Arrow binary format with JSON fallback
Why tywrap?
| Feature | tywrap | pythonia | node-calls-python | pymport | | ------------------------------- | --------- | --------- | ----------------- | --------- | | Auto-generated TypeScript types | ✅ | ❌ | ❌ | ❌ | | Browser / WASM (Pyodide) | ✅ | ❌ | ❌ | ❌ | | numpy / pandas type mappings | ✅ | ❌ | ❌ | ❌ | | Node.js + Bun + Deno | All three | Node only | Node only | Node only | | Apache Arrow binary transport | ✅ | ❌ | ❌ | ❌ |
Requirements
Node.js 20+ (or Bun 1.1+ / Deno 1.46+)
Python 3.10+ with
tywrap-ir:pip install tywrap-ir
Quick Start
npm install tywrap
pip install tywrap-ir # Python component for code generation
npx tywrap init # Create config (and package.json scripts if present)
npx tywrap generate # Generate wrapperstywrap and tywrap-ir are versioned independently. Install the latest
published release of each package unless you need to pin them explicitly.
For CI (or to verify a dependency upgrade didn’t change the generated surface):
npx tywrap generate --checkFor local Node development, tywrap/dev gives you real hot reload: watch local
Python package trees, regenerate wrappers, and swap the active bridge while
keeping the last known good state if regeneration fails.
import { NodeBridge } from 'tywrap/node';
import { setRuntimeBridge } from 'tywrap/runtime';
import * as math from './generated/math.generated.js';
const bridge = new NodeBridge({ pythonPath: 'python3' });
setRuntimeBridge(bridge);
const result = await math.sqrt(16); // 4If tywrap saves you time, a ⭐ on GitHub helps others find it.
Runtime Bridges
Node.js
import { NodeBridge } from 'tywrap/node';
const bridge = new NodeBridge({
pythonPath: 'python3',
virtualEnv: './venv',
timeoutMs: 30000,
});NodeBridge is the public Node runtime bridge. It runs in single-process mode by
default and also supports pooled execution through minProcesses,
maxProcesses, and maxConcurrentPerProcess.
OptimizedNodeBridge is now only a deprecated compatibility alias for older
deep imports. It is not part of the package exports and should not be used in
new code.
By default, NodeBridge inherits only PATH/PYTHON*/TYWRAP_* from process.env
to keep the subprocess environment minimal. Set inheritProcessEnv: true if you
need the full environment. Large JSONL responses are capped by maxLineLength
(defaults to TYWRAP_CODEC_MAX_BYTES when set, otherwise 1MB).
You can cap payload sizes with TYWRAP_CODEC_MAX_BYTES (responses) and
TYWRAP_REQUEST_MAX_BYTES (requests) to keep JSONL traffic bounded.
Development Hot Reload
import { startNodeWatchSession } from 'tywrap/dev';
import { NodeBridge } from 'tywrap/node';
const session = await startNodeWatchSession({
configFile: './tywrap.config.ts',
createBridge: async config =>
new NodeBridge({
pythonPath: config.runtime.node?.pythonPath ?? 'python3',
timeoutMs: config.runtime.node?.timeout ?? 30000,
}),
});- Node: full watch + wrapper regeneration + bridge swap
- Pyodide: use
createBridgeReloader(...)fromtywrap/devfor manual bridge replacement - HTTP: restart or redeploy the remote server outside tywrap
The Node watch session manages local package trees, refreshes nested directory watchers when package layouts change, and keeps the last known good generated output and bridge active if regeneration returns structured failures.
Browser (Pyodide)
import { PyodideBridge } from 'tywrap/pyodide';
const bridge = new PyodideBridge({
indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.28.0/full/',
});
await bridge.init();Deno / Bun
import { NodeBridge } from 'npm:tywrap'; // Deno
import { NodeBridge } from 'tywrap'; // BunConfiguration
// tywrap.config.ts
import { defineConfig } from 'tywrap';
export default defineConfig({
pythonModules: {
pandas: {
runtime: 'node',
typeHints: 'strict',
classes: ['DataFrame'],
functions: ['read_csv'],
},
numpy: {
runtime: 'node',
typeHints: 'strict',
alias: 'np',
},
},
output: { dir: './src/generated' },
});See Configuration Guide for all options.
Supported Data Types
| Python | TypeScript | Notes |
| ------------------------------------- | ------------------------ | ---------------- |
| numpy.ndarray | Uint8Array / array | Arrow or JSON |
| pandas.DataFrame | Arrow Table / object[] | Arrow or JSON |
| scipy.sparse.* | SparseMatrix | CSR, CSC, COO |
| torch.Tensor | TorchTensor | CPU only |
| sklearn estimator | SklearnEstimator | Params only |
| datetime, Decimal, UUID, Path | string | Standard formats |
For Arrow encoding with numpy/pandas:
import { registerArrowDecoder } from 'tywrap';
import { tableFromIPC } from 'apache-arrow';
registerArrowDecoder(bytes => tableFromIPC(bytes));Documentation
Contributing
npm install
npm testSee CONTRIBUTING.md for guidelines.
License
MIT © tywrap contributors
