or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdcode-execution.mdffi.mdfile-system.mdindex.mdinteroperability.mdio-streams.mdpackage-management.mdruntime-loading.md

index.mddocs/

0

# Pyodide

1

2

Pyodide is a Python distribution for the browser and Node.js based on WebAssembly that enables running Python code in web browsers and JavaScript environments with full bidirectional JavaScript-Python interoperability. It includes a complete CPython interpreter, the Python standard library, and many popular scientific Python packages pre-compiled for WebAssembly.

3

4

## Package Information

5

6

- **Package Name**: pyodide

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript with Python runtime

9

- **Installation**: `npm install pyodide`

10

11

## Core Imports

12

13

```javascript

14

import { loadPyodide } from "pyodide";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { loadPyodide } = require("pyodide");

21

```

22

23

## Basic Usage

24

25

```javascript

26

import { loadPyodide } from "pyodide";

27

28

// Load Pyodide runtime

29

const pyodide = await loadPyodide({

30

indexURL: "https://cdn.jsdelivr.net/pyodide/",

31

});

32

33

// Run Python code

34

const result = pyodide.runPython(`

35

import sys

36

sys.version

37

`);

38

console.log(result); // Python version string

39

40

// Install and use Python packages

41

await pyodide.loadPackage(["numpy", "pandas"]);

42

pyodide.runPython(`

43

import numpy as np

44

import pandas as pd

45

46

data = np.array([1, 2, 3, 4, 5])

47

df = pd.DataFrame({"values": data})

48

print(df.head())

49

`);

50

51

// JavaScript-Python interoperability

52

pyodide.globals.set("js_data", [1, 2, 3, 4, 5]);

53

const python_result = pyodide.runPython(`

54

js_data_from_python = js_data

55

sum(js_data_from_python)

56

`);

57

console.log(python_result); // 15

58

```

59

60

## Architecture

61

62

Pyodide is built around several key components:

63

64

- **WebAssembly Runtime**: CPython compiled to WebAssembly for browser/Node.js execution

65

- **Package System**: Integration with PyPI and a custom package repository for WebAssembly packages

66

- **Foreign Function Interface (FFI)**: Bidirectional conversion and proxy system between JavaScript and Python objects

67

- **File System**: Emscripten-based virtual file system with browser and Node.js integrations

68

- **I/O Streams**: Customizable stdin/stdout/stderr handling for different environments

69

- **Module System**: JavaScript module registration system allowing Python to import JS modules

70

71

## Capabilities

72

73

### Runtime Loading and Configuration

74

75

Core functionality for loading and configuring the Pyodide WebAssembly runtime with various options for different environments.

76

77

```javascript { .api }

78

function loadPyodide(options?: {

79

indexURL?: string;

80

packageCacheDir?: string;

81

lockFileURL?: string;

82

lockFileContents?: Lockfile | string | Promise<Lockfile | string>;

83

packageBaseUrl?: string;

84

fullStdLib?: boolean;

85

stdLibURL?: string;

86

stdin?: () => string;

87

stdout?: (msg: string) => void;

88

stderr?: (msg: string) => void;

89

jsglobals?: object;

90

_sysExecutable?: string;

91

args?: string[];

92

env?: { [key: string]: string };

93

packages?: string[];

94

pyproxyToStringRepr?: boolean;

95

enableRunUntilComplete?: boolean;

96

checkAPIVersion?: boolean;

97

fsInit?: (FS: FSType, info: { sitePackages: string }) => Promise<void>;

98

convertNullToNone?: boolean;

99

_makeSnapshot?: boolean;

100

_loadSnapshot?: Uint8Array | ArrayBuffer | PromiseLike<Uint8Array | ArrayBuffer>;

101

_snapshotDeserializer?: (obj: any) => any;

102

}): Promise<PyodideAPI>;

103

```

104

105

[Runtime Loading](./runtime-loading.md)

106

107

### Python Code Execution

108

109

Execute Python code from JavaScript with support for synchronous and asynchronous execution patterns.

110

111

```javascript { .api }

112

function runPython(

113

code: string,

114

options?: {

115

globals?: PyProxy;

116

locals?: PyProxy;

117

filename?: string;

118

}

119

): any;

120

121

function runPythonAsync(

122

code: string,

123

options?: {

124

globals?: PyProxy;

125

locals?: PyProxy;

126

filename?: string;

127

}

128

): Promise<any>;

129

```

130

131

[Code Execution](./code-execution.md)

132

133

### Package Management

134

135

Install and manage Python packages in the WebAssembly environment with automatic dependency resolution.

136

137

```javascript { .api }

138

function loadPackage(

139

packages: string | string[],

140

options?: {

141

messageCallback?: (message: string) => void;

142

errorCallback?: (message: string) => void;

143

checkIntegrity?: boolean;

144

}

145

): Promise<PackageData[]>;

146

147

function loadPackagesFromImports(

148

code: string,

149

options?: {

150

messageCallback?: (message: string) => void;

151

errorCallback?: (message: string) => void;

152

checkIntegrity?: boolean;

153

}

154

): Promise<PackageData[]>;

155

156

const loadedPackages: Map<string, PackageData>;

157

```

158

159

[Package Management](./package-management.md)

160

161

### JavaScript-Python Interoperability

162

163

Convert objects between JavaScript and Python, register JavaScript modules for Python import, and access Python objects from JavaScript.

164

165

```javascript { .api }

166

function toPy(

167

obj: any,

168

options?: {

169

depth?: number;

170

defaultConverter?: (

171

value: any,

172

converter: (value: any) => any,

173

cacheConversion: (input: any, output: any) => void

174

) => any;

175

}

176

): any;

177

178

function pyimport(moduleName: string): any;

179

180

function registerJsModule(name: string, module: object): void;

181

function unregisterJsModule(name: string): void;

182

183

const globals: PyProxy;

184

const pyodide_py: PyProxy;

185

```

186

187

[Interoperability](./interoperability.md)

188

189

### File System Operations

190

191

Access and manipulate the virtual file system with support for mounting host directories and browser file systems.

192

193

```javascript { .api }

194

const FS: {

195

readFile(path: string, options?: { encoding?: string }): string | Uint8Array;

196

writeFile(path: string, data: string | ArrayBufferView, options?: { encoding?: string }): void;

197

mkdir(path: string): void;

198

rmdir(path: string): void;

199

readdir(path: string): string[];

200

stat(path: string): FSStats;

201

mount(type: any, options: any, mountpoint: string): void;

202

// ... additional Emscripten FS methods

203

};

204

205

const PATH: {

206

dirname(path: string): string;

207

basename(path: string): string;

208

extname(path: string): string;

209

join(...paths: string[]): string;

210

normalize(path: string): string;

211

// ... additional path methods

212

};

213

214

function mountNodeFS(emscriptenPath: string, hostPath: string): void;

215

function mountNativeFS(

216

path: string,

217

fileSystemHandle: FileSystemDirectoryHandle

218

): Promise<NativeFS>;

219

```

220

221

[File System](./file-system.md)

222

223

### I/O Stream Management

224

225

Customize input/output handling for different environments and use cases.

226

227

```javascript { .api }

228

function setStdin(options?: {

229

stdin?: () => string;

230

read?: (buffer: Uint8Array) => number;

231

isatty?: boolean;

232

}): void;

233

234

function setStdout(options?: {

235

batched?: (output: string) => void;

236

raw?: (charCode: number) => void;

237

write?: (buffer: Uint8Array) => number;

238

isatty?: boolean;

239

}): void;

240

241

function setStderr(options?: {

242

batched?: (output: string) => void;

243

raw?: (charCode: number) => void;

244

write?: (buffer: Uint8Array) => number;

245

isatty?: boolean;

246

}): void;

247

```

248

249

[I/O Streams](./io-streams.md)

250

251

### Advanced Features

252

253

Advanced functionality including canvas integration, worker support, interrupt handling, debug control, and package information access.

254

255

```javascript { .api }

256

const canvas: {

257

setCanvas2D(canvas: HTMLCanvasElement): void;

258

getCanvas2D(): HTMLCanvasElement | undefined;

259

setCanvas3D(canvas: HTMLCanvasElement): void;

260

getCanvas3D(): HTMLCanvasElement | undefined;

261

};

262

263

function setInterruptBuffer(buffer: TypedArray): void;

264

function checkInterrupt(): void;

265

function registerComlink(Comlink: any): void;

266

267

function unpackArchive(

268

buffer: TypedArray | ArrayBuffer,

269

format: string,

270

options?: { extractDir?: string }

271

): void;

272

273

function setDebug(debug: boolean): boolean;

274

const lockfile: Lockfile;

275

const lockfileBaseUrl: string | undefined;

276

```

277

278

[Advanced Features](./advanced-features.md)

279

280

### Foreign Function Interface (FFI)

281

282

Comprehensive type system for seamless JavaScript-Python interoperability with proxy objects, type conversion, and error handling.

283

284

```javascript { .api }

285

import { ffi } from "pyodide/ffi";

286

287

const ffi: {

288

PyProxy: typeof PyProxy;

289

PyDict: typeof PyDict;

290

PySequence: typeof PySequence;

291

PyMutableSequence: typeof PyMutableSequence;

292

PyCallable: typeof PyCallable;

293

PyIterable: typeof PyIterable;

294

PyAsyncIterable: typeof PyAsyncIterable;

295

PyBuffer: typeof PyBuffer;

296

PythonError: typeof PythonError;

297

// ... additional FFI types

298

};

299

```

300

301

[Foreign Function Interface](./ffi.md)

302

303

## Core Types

304

305

```javascript { .api }

306

interface PyodideAPI {

307

loadPackage: typeof loadPackage;

308

loadPackagesFromImports: typeof loadPackagesFromImports;

309

loadedPackages: Map<string, PackageData>;

310

runPython: typeof runPython;

311

runPythonAsync: typeof runPythonAsync;

312

pyimport: typeof pyimport;

313

registerJsModule: typeof registerJsModule;

314

unregisterJsModule: typeof unregisterJsModule;

315

toPy: typeof toPy;

316

globals: PyProxy;

317

pyodide_py: PyProxy;

318

FS: FSType;

319

PATH: any;

320

canvas: CanvasInterface;

321

setStdin: typeof setStdin;

322

setStdout: typeof setStdout;

323

setStderr: typeof setStderr;

324

setInterruptBuffer: typeof setInterruptBuffer;

325

checkInterrupt: typeof checkInterrupt;

326

registerComlink: typeof registerComlink;

327

mountNodeFS: typeof mountNodeFS;

328

mountNativeFS: typeof mountNativeFS;

329

unpackArchive: typeof unpackArchive;

330

setDebug: (debug: boolean) => boolean;

331

lockfile: Lockfile;

332

lockfileBaseUrl: string | undefined;

333

ERRNO_CODES: { [code: string]: number };

334

version: string;

335

}

336

337

interface PackageData {

338

name: string;

339

version: string;

340

channel: string;

341

file_name: string;

342

install_dir: string;

343

sha256: string;

344

package_type: string;

345

imports: string[];

346

depends: string[];

347

}

348

349

type TypedArray =

350

| Int8Array

351

| Uint8Array

352

| Int16Array

353

| Uint16Array

354

| Int32Array

355

| Uint32Array

356

| Uint8ClampedArray

357

| Float32Array

358

| Float64Array;

359

360

interface Lockfile {

361

info: LockfileInfo;

362

packages: { [name: string]: LockfilePackage };

363

}

364

365

interface LockfileInfo {

366

arch: "wasm32";

367

abi_version: string;

368

platform: string;

369

version: string;

370

python: string;

371

}

372

373

interface LockfilePackage {

374

name: string;

375

version: string;

376

file_name: string;

377

package_type: PackageType;

378

install_dir: "site" | "dynlib";

379

sha256: string;

380

imports: string[];

381

depends: string[];

382

}

383

384

type PackageType =

385

| "package"

386

| "cpython_module"

387

| "shared_library"

388

| "static_library";

389

```