pyodide 0.18.0-alpha.1 → 0.19.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Pyodide Javascript package
1
+ # Pyodide JavaScript package
2
2
 
3
3
  <a href="https://www.npmjs.com/package/pyodide"><img src="https://img.shields.io/npm/v/pyodide" alt="npm"></a>
4
4
 
@@ -6,16 +6,18 @@
6
6
 
7
7
  Download and extract Pyodide packages from [Github
8
8
  releases](https://github.com/pyodide/pyodide/releases)
9
- (`pyodide-build-*.tar.bz2`). The version of the release need to match exactly the version of this package.
9
+ (`pyodide-build-*.tar.bz2`). The version of the release needs to match exactly the version of this package.
10
10
 
11
11
  Then you can load Pyodide in Node.js as follows,
12
- ```js
13
12
 
14
- let pyodide_pkg = await import('pyodide/pyodide.js');
13
+ ```js
14
+ let pyodide_pkg = await import("pyodide/pyodide.js");
15
15
 
16
- let pyodide = await pyodide_pkg.loadPyodide({ indexURL: "<pyodide artifacts folder>" });
16
+ let pyodide = await pyodide_pkg.loadPyodide({
17
+ indexURL: "<pyodide artifacts folder>",
18
+ });
17
19
 
18
- await pyodide.runPythonAsync('1+1')
20
+ await pyodide.runPythonAsync("1+1");
19
21
  ```
20
22
 
21
23
  **Note**: To start node REPL with support for top level await, use `node --experimental-repl-await`.
@@ -24,15 +26,15 @@ See the [documentation](https://pyodide.org/en/stable/) fore more details.
24
26
 
25
27
  ## Details
26
28
 
27
- The Javascript code in this package is responsible for the following tasks:
29
+ The JavaScript code in this package is responsible for the following tasks:
28
30
 
29
- 1. Defines the public [Javascript API](https://pyodide.org/en/stable/usage/api/js-api.html)
31
+ 1. Defines the public [JavaScript API](https://pyodide.org/en/stable/usage/api/js-api.html)
30
32
  - Package loading code to allow loading of other Python packages.
31
33
  - Can load
32
34
  [micropip](https://pyodide.org/en/stable/usage/api/micropip-api.html) to
33
35
  bootstrap loading of pure Python wheels
34
36
  2. Loads the CPython interpreter and the core/pyodide emscripten application
35
37
  which embeds the interpreter.
36
- 3. Injects the `js/pyodide` Javascript API into `sys.modules`. This is the
37
- final runtime dependency for core/pyodide & py/pyodide, so after this step
38
+ 3. Injects the `js/pyodide` JavaScript API into `sys.modules`. This is the
39
+ final runtime dependency for `core/pyodide` & `py/pyodide`, so after this step
38
40
  the interpreter is fully up and running.
package/api.js CHANGED
@@ -8,17 +8,18 @@ export { loadPackage, loadedPackages, isPyProxy };
8
8
  * @typedef {import('./pyproxy.gen').PyProxy} PyProxy
9
9
  * @typedef {import('./pyproxy.gen').TypedArray} TypedArray
10
10
  * @typedef {import('emscripten')} Emscripten
11
+ * @typedef {import('emscripten').Module.FS} FS
11
12
  */
12
13
 
13
14
  /**
14
15
  * An alias to the Python :py:mod:`pyodide` package.
15
16
  *
16
17
  * You can use this to call functions defined in the Pyodide Python package
17
- * from Javascript.
18
+ * from JavaScript.
18
19
  *
19
20
  * @type {PyProxy}
20
21
  */
21
- let pyodide_py = {}; // actually defined in runPythonSimple in loadPyodide (see pyodide.js)
22
+ let pyodide_py = {}; // actually defined in loadPyodide (see pyodide.js)
22
23
 
23
24
  /**
24
25
  *
@@ -29,10 +30,10 @@ let pyodide_py = {}; // actually defined in runPythonSimple in loadPyodide (see
29
30
  *
30
31
  * @type {PyProxy}
31
32
  */
32
- let globals = {}; // actually defined in runPythonSimple in loadPyodide (see pyodide.js)
33
+ let globals = {}; // actually defined in loadPyodide (see pyodide.js)
33
34
 
34
35
  /**
35
- * A Javascript error caused by a Python exception.
36
+ * A JavaScript error caused by a Python exception.
36
37
  *
37
38
  * In order to reduce the risk of large memory leaks, the ``PythonError``
38
39
  * contains no reference to the Python exception that caused it. You can find
@@ -74,19 +75,19 @@ export class PythonError {
74
75
  *
75
76
  * @type {string}
76
77
  */
77
- export let version = ""; // actually defined in runPythonSimple in loadPyodide (see pyodide.js)
78
+ export let version = ""; // actually defined in loadPyodide (see pyodide.js)
78
79
 
79
80
  /**
80
- * Runs a string of Python code from Javascript.
81
+ * Runs a string of Python code from JavaScript.
81
82
  *
82
83
  * The last part of the string may be an expression, in which case, its value
83
84
  * is returned.
84
85
  *
85
86
  * @param {string} code Python code to evaluate
86
- * @param {PyProxy} globals An optional Python dictionary to use as the globals.
87
+ * @param {PyProxy=} globals An optional Python dictionary to use as the globals.
87
88
  * Defaults to :any:`pyodide.globals`. Uses the Python API
88
89
  * :any:`pyodide.eval_code` to evaluate the code.
89
- * @returns {Py2JsResult} The result of the Python code translated to Javascript. See the
90
+ * @returns {Py2JsResult} The result of the Python code translated to JavaScript. See the
90
91
  * documentation for :any:`pyodide.eval_code` for more info.
91
92
  */
92
93
  export function runPython(code, globals = Module.globals) {
@@ -102,8 +103,8 @@ Module.runPython = runPython;
102
103
  */
103
104
 
104
105
  /**
105
- * Inspect a Python code chunk and use :js:func:`pyodide.loadPackage` to
106
- * install any known packages that the code chunk imports. Uses the Python API
106
+ * Inspect a Python code chunk and use :js:func:`pyodide.loadPackage` to install
107
+ * any known packages that the code chunk imports. Uses the Python API
107
108
  * :func:`pyodide.find\_imports` to inspect the code.
108
109
  *
109
110
  * For example, given the following code as input
@@ -113,7 +114,7 @@ Module.runPython = runPython;
113
114
  * import numpy as np x = np.array([1, 2, 3])
114
115
  *
115
116
  * :js:func:`loadPackagesFromImports` will call
116
- * ``pyodide.loadPackage(['numpy'])``. See also :js:func:`runPythonAsync`.
117
+ * ``pyodide.loadPackage(['numpy'])``.
117
118
  *
118
119
  * @param {string} code The code to inspect.
119
120
  * @param {LogFn=} messageCallback The ``messageCallback`` argument of
@@ -150,26 +151,17 @@ export async function loadPackagesFromImports(
150
151
  }
151
152
  }
152
153
 
153
- /**
154
- * Access a Python object in the global namespace from Javascript.
155
- *
156
- * @deprecated This function will be removed in version 0.18.0. Use
157
- * :any:`pyodide.globals.get('key') <pyodide.globals>` instead.
158
- *
159
- * @param {string} name Python variable name
160
- * @returns {Py2JsResult} The Python object translated to Javascript.
161
- */
162
- export function pyimport(name) {
163
- console.warn(
164
- "Access to the Python global namespace via pyodide.pyimport is deprecated and " +
165
- "will be removed in version 0.18.0. Use pyodide.globals.get('key') instead."
166
- );
167
- return Module.globals.get(name);
168
- }
169
154
  /**
170
155
  * Runs Python code using `PyCF_ALLOW_TOP_LEVEL_AWAIT
171
156
  * <https://docs.python.org/3/library/ast.html?highlight=pycf_allow_top_level_await#ast.PyCF_ALLOW_TOP_LEVEL_AWAIT>`_.
172
157
  *
158
+ * .. admonition:: Python imports
159
+ * :class: warning
160
+ *
161
+ * Since pyodide 0.18.0, you must call :js:func:`loadPackagesFromImports` to
162
+ * import any python packages referenced via `import` statements in your code.
163
+ * This function will no longer do it for you.
164
+ *
173
165
  * For example:
174
166
  *
175
167
  * .. code-block:: pyodide
@@ -178,36 +170,33 @@ export function pyimport(name) {
178
170
  * from js import fetch
179
171
  * response = await fetch("./packages.json")
180
172
  * packages = await response.json()
181
- * # If final statement is an expression, its value is returned to
182
- * Javascript len(packages['packages'].object_keys())
173
+ * # If final statement is an expression, its value is returned to JavaScript
174
+ * len(packages.packages.object_keys())
183
175
  * `);
184
- * console.log(result); // 72
176
+ * console.log(result); // 79
185
177
  *
186
178
  * @param {string} code Python code to evaluate
187
- * @returns {Py2JsResult} The result of the Python code translated to Javascript.
179
+ * @param {PyProxy=} globals An optional Python dictionary to use as the globals.
180
+ * Defaults to :any:`pyodide.globals`. Uses the Python API
181
+ * :any:`pyodide.eval_code_async` to evaluate the code.
182
+ * @returns {Py2JsResult} The result of the Python code translated to JavaScript.
188
183
  * @async
189
184
  */
190
- export async function runPythonAsync(code) {
191
- let coroutine = Module.pyodide_py.eval_code_async(code, Module.globals);
192
- try {
193
- let result = await coroutine;
194
- return result;
195
- } finally {
196
- coroutine.destroy();
197
- }
185
+ export async function runPythonAsync(code, globals = Module.globals) {
186
+ return await Module.pyodide_py.eval_code_async(code, globals);
198
187
  }
199
188
  Module.runPythonAsync = runPythonAsync;
200
189
 
201
190
  /**
202
- * Registers the Javascript object ``module`` as a Javascript module named
191
+ * Registers the JavaScript object ``module`` as a JavaScript module named
203
192
  * ``name``. This module can then be imported from Python using the standard
204
193
  * Python import system. If another module by the same name has already been
205
194
  * imported, this won't have much effect unless you also delete the imported
206
195
  * module from ``sys.modules``. This calls the ``pyodide_py`` API
207
196
  * :func:`pyodide.register_js_module`.
208
197
  *
209
- * @param {string} name Name of the Javascript module to add
210
- * @param {object} module Javascript object backing the module
198
+ * @param {string} name Name of the JavaScript module to add
199
+ * @param {object} module JavaScript object backing the module
211
200
  */
212
201
  export function registerJsModule(name, module) {
213
202
  Module.pyodide_py.register_js_module(name, module);
@@ -222,24 +211,24 @@ export function registerComlink(Comlink) {
222
211
  }
223
212
 
224
213
  /**
225
- * Unregisters a Javascript module with given name that has been previously
214
+ * Unregisters a JavaScript module with given name that has been previously
226
215
  * registered with :js:func:`pyodide.registerJsModule` or
227
- * :func:`pyodide.register_js_module`. If a Javascript module with that name
216
+ * :func:`pyodide.register_js_module`. If a JavaScript module with that name
228
217
  * does not already exist, will throw an error. Note that if the module has
229
218
  * already been imported, this won't have much effect unless you also delete
230
219
  * the imported module from ``sys.modules``. This calls the ``pyodide_py`` API
231
220
  * :func:`pyodide.unregister_js_module`.
232
221
  *
233
- * @param {string} name Name of the Javascript module to remove
222
+ * @param {string} name Name of the JavaScript module to remove
234
223
  */
235
224
  export function unregisterJsModule(name) {
236
225
  Module.pyodide_py.unregister_js_module(name);
237
226
  }
238
227
 
239
228
  /**
240
- * Convert the Javascript object to a Python object as best as possible.
229
+ * Convert the JavaScript object to a Python object as best as possible.
241
230
  *
242
- * This is similar to :any:`JsProxy.to_py` but for use from Javascript. If the
231
+ * This is similar to :any:`JsProxy.to_py` but for use from JavaScript. If the
243
232
  * object is immutable or a :any:`PyProxy`, it will be returned unchanged. If
244
233
  * the object cannot be converted into Python, it will be returned unchanged.
245
234
  *
@@ -247,7 +236,7 @@ export function unregisterJsModule(name) {
247
236
  *
248
237
  * @param {*} obj
249
238
  * @param {object} options
250
- * @param {number} options.depth Optional argument to limit the depth of the
239
+ * @param {number=} options.depth Optional argument to limit the depth of the
251
240
  * conversion.
252
241
  * @returns {PyProxy} The object converted to Python.
253
242
  */
@@ -270,9 +259,13 @@ export function toPy(obj, { depth = -1 } = {}) {
270
259
  let result = 0;
271
260
  try {
272
261
  obj_id = Module.hiwire.new_value(obj);
273
- py_result = Module.__js2python_convert(obj_id, new Map(), depth);
274
- if (py_result === 0) {
275
- Module._pythonexc2js();
262
+ try {
263
+ py_result = Module.js2python_convert(obj_id, new Map(), depth);
264
+ } catch (e) {
265
+ if (e instanceof Module._PropagatePythonError) {
266
+ Module._pythonexc2js();
267
+ }
268
+ throw e;
276
269
  }
277
270
  if (Module._JsProxy_Check(py_result)) {
278
271
  // Oops, just created a JsProxy. Return the original object.
@@ -290,6 +283,56 @@ export function toPy(obj, { depth = -1 } = {}) {
290
283
  return Module.hiwire.pop_value(result);
291
284
  }
292
285
 
286
+ /**
287
+ * Imports a module and returns it.
288
+ * Warning: this function has a completely different behavior than the old removed pyimport function!
289
+ * ``pyimport`` is roughly equivalent to:
290
+ *
291
+ * .. code-block:: pyodide
292
+ *
293
+ * pyodide.runPython(`import ${pkgname}; ${pkgname}`);
294
+ *
295
+ * except that the global namespace will not change.
296
+ * Example:
297
+ *
298
+ * .. code-block:: pyodide
299
+ *
300
+ * let sysmodule = pyodide.pyimport("sys");
301
+ * let recursionLimit = sys.getrecursionlimit();
302
+ *
303
+ * The best way to run Python code with Pyodide is
304
+ * 1. write a Python package,
305
+ * 2. load your Python package into the Pyodide (Emscripten) file system,
306
+ * 3. import the package with `let mypkg = pyodide.pyimport("mypkgname")`,
307
+ * 4. call into your package with `mypkg.some_api(some_args)`.
308
+ *
309
+ * @param {string} mod_name The name of the module to import
310
+ * @returns A PyProxy for the imported module
311
+ */
312
+ export function pyimport(mod_name) {
313
+ return Module.importlib.import_module(mod_name);
314
+ }
315
+
316
+ /**
317
+ * Unpack an archive into a target directory.
318
+ *
319
+ * @param {ArrayBuffer} buffer The archive as an ArrayBuffer (it's also fine to pass a TypedArray).
320
+ * @param {string} format The format of the archive. Should be one of the formats recognized by `shutil.unpack_archive`.
321
+ * By default the options are 'bztar', 'gztar', 'tar', 'zip', and 'wheel'. Several synonyms are accepted for each format, e.g.,
322
+ * for 'gztar' any of '.gztar', '.tar.gz', '.tgz', 'tar.gz' or 'tgz' are considered to be synonyms.
323
+ *
324
+ * @param {string=} extract_dir The directory to unpack the archive into. Defaults to the working directory.
325
+ */
326
+ export function unpackArchive(buffer, format, extract_dir) {
327
+ if (!Module._util_module) {
328
+ Module._util_module = pyimport("pyodide._util");
329
+ }
330
+ Module._util_module.unpack_buffer_archive.callKwargs(buffer, {
331
+ format,
332
+ extract_dir,
333
+ });
334
+ }
335
+
293
336
  /**
294
337
  * @private
295
338
  */
@@ -301,11 +344,34 @@ Module.saveState = () => Module.pyodide_py._state.save_state();
301
344
  Module.restoreState = (state) => Module.pyodide_py._state.restore_state(state);
302
345
 
303
346
  /**
347
+ * Sets the interrupt buffer to be `interrupt_buffer`. This is only useful when
348
+ * Pyodide is used in a webworker. The buffer should be a `SharedArrayBuffer`
349
+ * shared with the main browser thread (or another worker). To request an
350
+ * interrupt, a `2` should be written into `interrupt_buffer` (2 is the posix
351
+ * constant for SIGINT).
352
+ *
304
353
  * @param {TypedArray} interrupt_buffer
305
354
  */
306
- function setInterruptBuffer(interrupt_buffer) {}
307
- setInterruptBuffer = Module.setInterruptBuffer;
308
- export { setInterruptBuffer };
355
+ export function setInterruptBuffer(interrupt_buffer) {
356
+ Module.interrupt_buffer = interrupt_buffer;
357
+ Module._set_pyodide_callback(!!interrupt_buffer);
358
+ }
359
+
360
+ /**
361
+ * Throws a KeyboardInterrupt error if a KeyboardInterrupt has been requested
362
+ * via the interrupt buffer.
363
+ *
364
+ * This can be used to enable keyboard interrupts during execution of JavaScript
365
+ * code, just as `PyErr_CheckSignals` is used to enable keyboard interrupts
366
+ * during execution of C code.
367
+ */
368
+ export function checkInterrupt() {
369
+ if (Module.interrupt_buffer[0] === 2) {
370
+ Module.interrupt_buffer[0] = 0;
371
+ Module._PyErr_SetInterrupt();
372
+ Module.runPython("");
373
+ }
374
+ }
309
375
 
310
376
  export function makePublicAPI() {
311
377
  /**
@@ -318,15 +384,14 @@ export function makePublicAPI() {
318
384
  * which can be used to extend the in-memory filesystem with features like `persistence
319
385
  * <https://emscripten.org/docs/api_reference/Filesystem-API.html#persistent-data>`_.
320
386
  *
321
- * While all of the file systems implementations are enabled, only the default
387
+ * While all the file systems implementations are enabled, only the default
322
388
  * ``MEMFS`` is guaranteed to work in all runtime settings. The implementations
323
389
  * are available as members of ``FS.filesystems``:
324
390
  * ``IDBFS``, ``NODEFS``, ``PROXYFS``, ``WORKERFS``.
325
391
  *
326
- * @type {FS} The Emscripten File System API.
392
+ * @type {FS}
327
393
  */
328
394
  const FS = Module.FS;
329
-
330
395
  let namespace = {
331
396
  globals,
332
397
  FS,
@@ -336,13 +401,15 @@ export function makePublicAPI() {
336
401
  loadPackagesFromImports,
337
402
  loadedPackages,
338
403
  isPyProxy,
339
- pyimport,
340
404
  runPython,
341
405
  runPythonAsync,
342
406
  registerJsModule,
343
407
  unregisterJsModule,
344
408
  setInterruptBuffer,
409
+ checkInterrupt,
345
410
  toPy,
411
+ pyimport,
412
+ unpackArchive,
346
413
  registerComlink,
347
414
  PythonError,
348
415
  PyBuffer,
package/index.test-d.ts CHANGED
@@ -22,6 +22,16 @@ async function main() {
22
22
  loadPyodide({ indexURL: "blah", fullStdLib: true })
23
23
  );
24
24
 
25
+ expectType<Promise<typeof pyodide>>(
26
+ loadPyodide({
27
+ indexURL: "blah",
28
+ fullStdLib: true,
29
+ stdin: () => "a string",
30
+ stdout: (x: string) => {},
31
+ stderr: (err: string) => {},
32
+ })
33
+ );
34
+
25
35
  expectType<PyProxy>(pyodide.globals);
26
36
 
27
37
  let x: Py2JsResult;
@@ -39,29 +49,32 @@ async function main() {
39
49
 
40
50
  expectType<Promise<void>>(pyodide.loadPackagesFromImports("import some_pkg"));
41
51
  expectType<Promise<void>>(
42
- pyodide.loadPackagesFromImports("import some_pkg", (x) => console.log(x))
52
+ pyodide.loadPackagesFromImports("import some_pkg", (x: any) =>
53
+ console.log(x)
54
+ )
43
55
  );
44
56
  expectType<Promise<void>>(
45
57
  pyodide.loadPackagesFromImports(
46
58
  "import some_pkg",
47
- (x) => console.log(x),
48
- (x) => console.warn(x)
59
+ (x: any) => console.log(x),
60
+ (x: any) => console.warn(x)
49
61
  )
50
62
  );
51
63
 
52
64
  expectType<Promise<void>>(pyodide.loadPackage("blah"));
53
65
  expectType<Promise<void>>(pyodide.loadPackage(["blah", "blah2"]));
54
- expectType<Promise<void>>(pyodide.loadPackage("blah", (x) => console.log(x)));
66
+ expectType<Promise<void>>(
67
+ pyodide.loadPackage("blah", (x: any) => console.log(x))
68
+ );
55
69
  expectType<Promise<void>>(
56
70
  pyodide.loadPackage(
57
71
  ["blah", "blah2"],
58
- (x) => console.log(x),
59
- (x) => console.warn(x)
72
+ (x: any) => console.log(x),
73
+ (x: any) => console.warn(x)
60
74
  )
61
75
  );
62
76
  expectType<Promise<void>>(pyodide.loadPackage(px));
63
77
 
64
- expectType<Py2JsResult>(pyodide.pyimport("blah"));
65
78
  expectType<PyProxy>(pyodide.pyodide_py);
66
79
  expectType<void>(pyodide.registerJsModule("blah", { a: 7 }));
67
80
  expectType<void>(pyodide.unregisterJsModule("blah"));
@@ -76,10 +89,10 @@ async function main() {
76
89
  expectType<void>(px.destroy());
77
90
  expectType<any>(px.toJs());
78
91
  expectType<any>(px.toJs({}));
79
- expectType<any>(px.toJs({depth : 10}));
80
- expectType<any>(px.toJs({create_pyproxies : false}));
81
- expectType<any>(px.toJs({create_pyproxies : true}));
82
- expectType<any>(px.toJs({pyproxies : []}));
92
+ expectType<any>(px.toJs({ depth: 10 }));
93
+ expectType<any>(px.toJs({ create_pyproxies: false }));
94
+ expectType<any>(px.toJs({ create_pyproxies: true }));
95
+ expectType<any>(px.toJs({ pyproxies: [] }));
83
96
  expectType<string>(px.toString());
84
97
  expectType<string>(px.type);
85
98