pyodide 0.20.0 → 0.21.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/api.ts DELETED
@@ -1,495 +0,0 @@
1
- import { Module, API, Hiwire } from "./module";
2
- import { loadPackage, loadedPackages } from "./load-package";
3
- import { isPyProxy, PyBuffer, PyProxy, TypedArray } from "./pyproxy.gen";
4
- import { PythonError } from "./error_handling.gen";
5
- export { loadPackage, loadedPackages, isPyProxy };
6
-
7
- /**
8
- * An alias to the Python :py:mod:`pyodide` package.
9
- *
10
- * You can use this to call functions defined in the Pyodide Python package
11
- * from JavaScript.
12
- */
13
- export let pyodide_py: PyProxy; // actually defined in loadPyodide (see pyodide.js)
14
-
15
- /**
16
- *
17
- * An alias to the global Python namespace.
18
- *
19
- * For example, to access a variable called ``foo`` in the Python global
20
- * scope, use ``pyodide.globals.get("foo")``
21
- */
22
- export let globals: PyProxy; // actually defined in loadPyodide (see pyodide.js)
23
-
24
- /**
25
- *
26
- * The Pyodide version.
27
- *
28
- * It can be either the exact release version (e.g. ``0.1.0``), or
29
- * the latest release version followed by the number of commits since, and
30
- * the git hash of the current commit (e.g. ``0.1.0-1-bd84646``).
31
- */
32
- export let version: string = ""; // actually defined in loadPyodide (see pyodide.js)
33
-
34
- let runPythonPositionalGlobalsDeprecationWarned = false;
35
- /**
36
- * Runs a string of Python code from JavaScript, using :any:`pyodide.eval_code`
37
- * to evaluate the code. If the last statement in the Python code is an
38
- * expression (and the code doesn't end with a semicolon), the value of the
39
- * expression is returned.
40
- *
41
- * .. admonition:: Positional globals argument
42
- * :class: warning
43
- *
44
- * In Pyodide v0.19, this function took the globals parameter as a positional
45
- * argument rather than as a named argument. In v0.20 this will still work
46
- * but it is deprecated. It will be removed in v0.21.
47
- *
48
- * @param code Python code to evaluate
49
- * @param options
50
- * @param options.globals An optional Python dictionary to use as the globals.
51
- * Defaults to :any:`pyodide.globals`.
52
- * @returns The result of the Python code translated to JavaScript. See the
53
- * documentation for :any:`pyodide.eval_code` for more info.
54
- */
55
- export function runPython(
56
- code: string,
57
- options: { globals?: PyProxy } = {}
58
- ): any {
59
- if (API.isPyProxy(options)) {
60
- options = { globals: options as PyProxy };
61
- if (!runPythonPositionalGlobalsDeprecationWarned) {
62
- console.warn(
63
- "Passing a PyProxy as the second argument to runPython is deprecated and will be removed in v0.21. Use 'runPython(code, {globals : some_dict})' instead."
64
- );
65
- runPythonPositionalGlobalsDeprecationWarned = true;
66
- }
67
- }
68
- if (!options.globals) {
69
- options.globals = API.globals;
70
- }
71
- return API.pyodide_py.eval_code(code, options.globals);
72
- }
73
- API.runPython = runPython;
74
-
75
- /**
76
- * Inspect a Python code chunk and use :js:func:`pyodide.loadPackage` to install
77
- * any known packages that the code chunk imports. Uses the Python API
78
- * :func:`pyodide.find\_imports` to inspect the code.
79
- *
80
- * For example, given the following code as input
81
- *
82
- * .. code-block:: python
83
- *
84
- * import numpy as np x = np.array([1, 2, 3])
85
- *
86
- * :js:func:`loadPackagesFromImports` will call
87
- * ``pyodide.loadPackage(['numpy'])``.
88
- *
89
- * @param code The code to inspect.
90
- * @param messageCallback The ``messageCallback`` argument of
91
- * :any:`pyodide.loadPackage` (optional).
92
- * @param errorCallback The ``errorCallback`` argument of
93
- * :any:`pyodide.loadPackage` (optional).
94
- * @async
95
- */
96
- export async function loadPackagesFromImports(
97
- code: string,
98
- messageCallback?: (msg: string) => void,
99
- errorCallback?: (err: string) => void
100
- ) {
101
- let pyimports = API.pyodide_py.find_imports(code);
102
- let imports;
103
- try {
104
- imports = pyimports.toJs();
105
- } finally {
106
- pyimports.destroy();
107
- }
108
- if (imports.length === 0) {
109
- return;
110
- }
111
-
112
- let packageNames = API._import_name_to_package_name;
113
- let packages: Set<string> = new Set();
114
- for (let name of imports) {
115
- if (packageNames.has(name)) {
116
- packages.add(packageNames.get(name));
117
- }
118
- }
119
- if (packages.size) {
120
- await loadPackage(Array.from(packages), messageCallback, errorCallback);
121
- }
122
- }
123
-
124
- /**
125
- * Run a Python code string with top level await using
126
- * :any:`pyodide.eval_code_async` to evaluate the code. Returns a promise which
127
- * resolves when execution completes. If the last statement in the Python code
128
- * is an expression (and the code doesn't end with a semicolon), the returned
129
- * promise will resolve to the value of this expression.
130
- *
131
- * For example:
132
- *
133
- * .. code-block:: pyodide
134
- *
135
- * let result = await pyodide.runPythonAsync(`
136
- * from js import fetch
137
- * response = await fetch("./packages.json")
138
- * packages = await response.json()
139
- * # If final statement is an expression, its value is returned to JavaScript
140
- * len(packages.packages.object_keys())
141
- * `);
142
- * console.log(result); // 79
143
- *
144
- * .. admonition:: Python imports
145
- * :class: warning
146
- *
147
- * Since pyodide 0.18.0, you must call :js:func:`loadPackagesFromImports` to
148
- * import any python packages referenced via `import` statements in your
149
- * code. This function will no longer do it for you.
150
- *
151
- * .. admonition:: Positional globals argument
152
- * :class: warning
153
- *
154
- * In Pyodide v0.19, this function took the globals parameter as a
155
- * positional argument rather than as a named argument. In v0.20 this will
156
- * still work but it is deprecated. It will be removed in v0.21.
157
- *
158
- * @param code Python code to evaluate
159
- * @param options
160
- * @param options.globals An optional Python dictionary to use as the globals.
161
- * Defaults to :any:`pyodide.globals`.
162
- * @returns The result of the Python code translated to JavaScript.
163
- * @async
164
- */
165
- export async function runPythonAsync(
166
- code: string,
167
- options: { globals?: PyProxy } = {}
168
- ): Promise<any> {
169
- if (API.isPyProxy(options)) {
170
- options = { globals: options as PyProxy };
171
- if (!runPythonPositionalGlobalsDeprecationWarned) {
172
- console.warn(
173
- "Passing a PyProxy as the second argument to runPythonAsync is deprecated and will be removed in v0.21. Use 'runPythonAsync(code, {globals : some_dict})' instead."
174
- );
175
- runPythonPositionalGlobalsDeprecationWarned = true;
176
- }
177
- }
178
- if (!options.globals) {
179
- options.globals = API.globals;
180
- }
181
- return await API.pyodide_py.eval_code_async(code, options.globals);
182
- }
183
- API.runPythonAsync = runPythonAsync;
184
-
185
- /**
186
- * Registers the JavaScript object ``module`` as a JavaScript module named
187
- * ``name``. This module can then be imported from Python using the standard
188
- * Python import system. If another module by the same name has already been
189
- * imported, this won't have much effect unless you also delete the imported
190
- * module from ``sys.modules``. This calls the {any}`pyodide_py` API
191
- * :func:`pyodide.register_js_module`.
192
- *
193
- * @param name Name of the JavaScript module to add
194
- * @param module JavaScript object backing the module
195
- */
196
- export function registerJsModule(name: string, module: object) {
197
- API.pyodide_py.register_js_module(name, module);
198
- }
199
-
200
- /**
201
- * Tell Pyodide about Comlink.
202
- * Necessary to enable importing Comlink proxies into Python.
203
- */
204
- export function registerComlink(Comlink: any) {
205
- API._Comlink = Comlink;
206
- }
207
-
208
- /**
209
- * Unregisters a JavaScript module with given name that has been previously
210
- * registered with :js:func:`pyodide.registerJsModule` or
211
- * :func:`pyodide.register_js_module`. If a JavaScript module with that name
212
- * does not already exist, will throw an error. Note that if the module has
213
- * already been imported, this won't have much effect unless you also delete
214
- * the imported module from ``sys.modules``. This calls the :any:`pyodide_py` API
215
- * :func:`pyodide.unregister_js_module`.
216
- *
217
- * @param name Name of the JavaScript module to remove
218
- */
219
- export function unregisterJsModule(name: string) {
220
- API.pyodide_py.unregister_js_module(name);
221
- }
222
-
223
- /**
224
- * Convert the JavaScript object to a Python object as best as possible.
225
- *
226
- * This is similar to :any:`JsProxy.to_py` but for use from JavaScript. If the
227
- * object is immutable or a :any:`PyProxy`, it will be returned unchanged. If
228
- * the object cannot be converted into Python, it will be returned unchanged.
229
- *
230
- * See :ref:`type-translations-jsproxy-to-py` for more information.
231
- *
232
- * @param obj
233
- * @param options
234
- * @returns The object converted to Python.
235
- */
236
- export function toPy(
237
- obj: any,
238
- {
239
- depth,
240
- defaultConverter,
241
- }: {
242
- /**
243
- * Optional argument to limit the depth of the conversion.
244
- */
245
- depth: number;
246
- /**
247
- * Optional argument to convert objects with no default conversion. See the
248
- * documentation of :any:`JsProxy.to_py`.
249
- */
250
- defaultConverter?: (
251
- value: any,
252
- converter: (value: any) => any,
253
- cacheConversion: (input: any, output: any) => any
254
- ) => any;
255
- } = { depth: -1 }
256
- ): any {
257
- // No point in converting these, it'd be dumb to proxy them so they'd just
258
- // get converted back by `js2python` at the end
259
- switch (typeof obj) {
260
- case "string":
261
- case "number":
262
- case "boolean":
263
- case "bigint":
264
- case "undefined":
265
- return obj;
266
- }
267
- if (!obj || API.isPyProxy(obj)) {
268
- return obj;
269
- }
270
- let obj_id = 0;
271
- let py_result = 0;
272
- let result = 0;
273
- try {
274
- obj_id = Hiwire.new_value(obj);
275
- try {
276
- py_result = Module.js2python_convert(obj_id, { depth, defaultConverter });
277
- } catch (e) {
278
- if (e instanceof Module._PropagatePythonError) {
279
- Module._pythonexc2js();
280
- }
281
- throw e;
282
- }
283
- if (Module._JsProxy_Check(py_result)) {
284
- // Oops, just created a JsProxy. Return the original object.
285
- return obj;
286
- // return Module.pyproxy_new(py_result);
287
- }
288
- result = Module._python2js(py_result);
289
- if (result === 0) {
290
- Module._pythonexc2js();
291
- }
292
- } finally {
293
- Hiwire.decref(obj_id);
294
- Module._Py_DecRef(py_result);
295
- }
296
- return Hiwire.pop_value(result);
297
- }
298
-
299
- /**
300
- * Imports a module and returns it.
301
- *
302
- * .. admonition:: Warning
303
- * :class: warning
304
- *
305
- * This function has a completely different behavior than the old removed pyimport function!
306
- *
307
- * ``pyimport`` is roughly equivalent to:
308
- *
309
- * .. code-block:: js
310
- *
311
- * pyodide.runPython(`import ${pkgname}; ${pkgname}`);
312
- *
313
- * except that the global namespace will not change.
314
- *
315
- * Example:
316
- *
317
- * .. code-block:: js
318
- *
319
- * let sysmodule = pyodide.pyimport("sys");
320
- * let recursionLimit = sys.getrecursionlimit();
321
- *
322
- * @param mod_name The name of the module to import
323
- * @returns A PyProxy for the imported module
324
- */
325
- export function pyimport(mod_name: string): PyProxy {
326
- return API.importlib.import_module(mod_name);
327
- }
328
-
329
- let unpackArchivePositionalExtractDirDeprecationWarned = false;
330
- /**
331
- * Unpack an archive into a target directory.
332
- *
333
- * .. admonition:: Positional globals argument :class: warning
334
- *
335
- * In Pyodide v0.19, this function took the extract_dir parameter as a
336
- * positional argument rather than as a named argument. In v0.20 this will
337
- * still work but it is deprecated. It will be removed in v0.21.
338
- *
339
- * @param buffer The archive as an ArrayBuffer or TypedArray.
340
- * @param format The format of the archive. Should be one of the formats
341
- * recognized by `shutil.unpack_archive`. By default the options are 'bztar',
342
- * 'gztar', 'tar', 'zip', and 'wheel'. Several synonyms are accepted for each
343
- * format, e.g., for 'gztar' any of '.gztar', '.tar.gz', '.tgz', 'tar.gz' or
344
- * 'tgz' are considered to be synonyms.
345
- *
346
- * @param options
347
- * @param options.extractDir The directory to unpack the archive into. Defaults
348
- * to the working directory.
349
- */
350
- export function unpackArchive(
351
- buffer: TypedArray,
352
- format: string,
353
- options: {
354
- extractDir?: string;
355
- } = {}
356
- ) {
357
- if (typeof options === "string") {
358
- if (!unpackArchivePositionalExtractDirDeprecationWarned) {
359
- console.warn(
360
- "Passing a string as the third argument to unpackArchive is deprecated and will be removed in v0.21. Instead use { extract_dir : 'some_path' }"
361
- );
362
- unpackArchivePositionalExtractDirDeprecationWarned = true;
363
- }
364
- options = { extractDir: options };
365
- }
366
- let extract_dir = options.extractDir;
367
- API.package_loader.unpack_buffer.callKwargs({
368
- buffer,
369
- format,
370
- extract_dir,
371
- });
372
- }
373
-
374
- /**
375
- * @private
376
- */
377
- API.saveState = () => API.pyodide_py._state.save_state();
378
-
379
- /**
380
- * @private
381
- */
382
- API.restoreState = (state: any) => API.pyodide_py._state.restore_state(state);
383
-
384
- /**
385
- * Sets the interrupt buffer to be ``interrupt_buffer``. This is only useful
386
- * when Pyodide is used in a webworker. The buffer should be a
387
- * ``SharedArrayBuffer`` shared with the main browser thread (or another
388
- * worker). In that case, signal ``signum`` may be sent by writing ``signum``
389
- * into the interrupt buffer. If ``signum`` does not satisfy 0 < ``signum`` <
390
- * ``NSIG`` it will be silently ignored. NSIG is 65 (internally signals are
391
- * indicated by a bitflag).
392
- *
393
- * You can disable interrupts by calling `setInterruptBuffer(undefined)`.
394
- *
395
- * If you wish to trigger a ``KeyboardInterrupt``, write ``SIGINT`` (a 2), into
396
- * the interrupt buffer.
397
- *
398
- * By default ``SIGINT`` raises a ``KeyboardInterrupt`` and all other signals
399
- * are ignored. You can install custom signal handlers with the signal module.
400
- * Even signals that normally have special meaning and can't be overridden like
401
- * ``SIGKILL`` and ``SIGSEGV`` are ignored by default and can be used for any
402
- * purpose you like.
403
- */
404
- export function setInterruptBuffer(interrupt_buffer: TypedArray) {
405
- Module.HEAP8[Module._Py_EMSCRIPTEN_SIGNAL_HANDLING] = !!interrupt_buffer;
406
- Module.Py_EmscriptenSignalBuffer = interrupt_buffer;
407
- }
408
-
409
- /**
410
- * Throws a KeyboardInterrupt error if a KeyboardInterrupt has been requested
411
- * via the interrupt buffer.
412
- *
413
- * This can be used to enable keyboard interrupts during execution of JavaScript
414
- * code, just as ``PyErr_CheckSignals`` is used to enable keyboard interrupts
415
- * during execution of C code.
416
- */
417
- export function checkInterrupt() {
418
- if (Module.__PyErr_CheckSignals()) {
419
- Module._pythonexc2js();
420
- }
421
- }
422
-
423
- export type PyodideInterface = {
424
- globals: typeof globals;
425
- FS: typeof FS;
426
- pyodide_py: typeof pyodide_py;
427
- version: typeof version;
428
- loadPackage: typeof loadPackage;
429
- loadPackagesFromImports: typeof loadPackagesFromImports;
430
- loadedPackages: typeof loadedPackages;
431
- isPyProxy: typeof isPyProxy;
432
- runPython: typeof runPython;
433
- runPythonAsync: typeof runPythonAsync;
434
- registerJsModule: typeof registerJsModule;
435
- unregisterJsModule: typeof unregisterJsModule;
436
- setInterruptBuffer: typeof setInterruptBuffer;
437
- checkInterrupt: typeof checkInterrupt;
438
- toPy: typeof toPy;
439
- pyimport: typeof pyimport;
440
- unpackArchive: typeof unpackArchive;
441
- registerComlink: typeof registerComlink;
442
- PythonError: typeof PythonError;
443
- PyBuffer: typeof PyBuffer;
444
- };
445
-
446
- /**
447
- * An alias to the `Emscripten File System API
448
- * <https://emscripten.org/docs/api_reference/Filesystem-API.html>`_.
449
- *
450
- * This provides a wide range of POSIX-`like` file/device operations, including
451
- * `mount
452
- * <https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.mount>`_
453
- * which can be used to extend the in-memory filesystem with features like `persistence
454
- * <https://emscripten.org/docs/api_reference/Filesystem-API.html#persistent-data>`_.
455
- *
456
- * While all the file systems implementations are enabled, only the default
457
- * ``MEMFS`` is guaranteed to work in all runtime settings. The implementations
458
- * are available as members of ``FS.filesystems``:
459
- * ``IDBFS``, ``NODEFS``, ``PROXYFS``, ``WORKERFS``.
460
- */
461
- export let FS: any;
462
-
463
- /**
464
- * @private
465
- */
466
- export function makePublicAPI(): PyodideInterface {
467
- FS = Module.FS;
468
- let namespace = {
469
- globals,
470
- FS,
471
- pyodide_py,
472
- version,
473
- loadPackage,
474
- loadPackagesFromImports,
475
- loadedPackages,
476
- isPyProxy,
477
- runPython,
478
- runPythonAsync,
479
- registerJsModule,
480
- unregisterJsModule,
481
- setInterruptBuffer,
482
- checkInterrupt,
483
- toPy,
484
- pyimport,
485
- unpackArchive,
486
- registerComlink,
487
- PythonError,
488
- PyBuffer,
489
- _module: Module,
490
- _api: API,
491
- };
492
-
493
- API.public_api = namespace;
494
- return namespace;
495
- }
package/compat.ts DELETED
@@ -1,146 +0,0 @@
1
- // Detect if we're in node
2
- declare var process: any;
3
-
4
- export const IN_NODE =
5
- typeof process !== "undefined" &&
6
- process.release &&
7
- process.release.name === "node" &&
8
- typeof process.browser ===
9
- "undefined"; /* This last condition checks if we run the browser shim of process */
10
-
11
- let nodePathMod: any;
12
- let nodeFetch: any;
13
- let nodeVmMod: any;
14
- /** @private */
15
- export let nodeFsPromisesMod: any;
16
-
17
- declare var globalThis: {
18
- importScripts: (url: string) => void;
19
- document?: any;
20
- };
21
-
22
- /**
23
- * If we're in node, it's most convenient to import various node modules on
24
- * initialization. Otherwise, this does nothing.
25
- * @private
26
- */
27
- export async function initNodeModules() {
28
- if (!IN_NODE) {
29
- return;
30
- }
31
- // @ts-ignore
32
- nodePathMod = (await import(/* webpackIgnore: true */ "path")).default;
33
- nodeFsPromisesMod = await import(/* webpackIgnore: true */ "fs/promises");
34
- // @ts-ignore
35
- nodeFetch = (await import(/* webpackIgnore: true */ "node-fetch")).default;
36
- // @ts-ignore
37
- nodeVmMod = (await import(/* webpackIgnore: true */ "vm")).default;
38
- }
39
-
40
- /**
41
- * Load a binary file, only for use in Node. If the path explicitly is a URL,
42
- * then fetch from a URL, else load from the file system.
43
- * @param indexURL base path to resolve relative paths
44
- * @param path the path to load
45
- * @returns An ArrayBuffer containing the binary data
46
- * @private
47
- */
48
- async function node_loadBinaryFile(
49
- indexURL: string,
50
- path: string
51
- ): Promise<Uint8Array> {
52
- if (path.includes("://")) {
53
- let response = await nodeFetch(path);
54
- if (!response.ok) {
55
- throw new Error(`Failed to load '${path}': request failed.`);
56
- }
57
- return await response.arrayBuffer();
58
- } else {
59
- const data = await nodeFsPromisesMod.readFile(`${indexURL}${path}`);
60
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
61
- }
62
- }
63
-
64
- /**
65
- * Load a binary file, only for use in browser. Resolves relative paths against
66
- * indexURL.
67
- *
68
- * @param indexURL base path to resolve relative paths
69
- * @param path the path to load
70
- * @returns A Uint8Array containing the binary data
71
- * @private
72
- */
73
- async function browser_loadBinaryFile(
74
- indexURL: string,
75
- path: string
76
- ): Promise<Uint8Array> {
77
- // @ts-ignore
78
- const base = new URL(indexURL, location);
79
- const url = new URL(path, base);
80
- // @ts-ignore
81
- let response = await fetch(url);
82
- if (!response.ok) {
83
- throw new Error(`Failed to load '${url}': request failed.`);
84
- }
85
- return new Uint8Array(await response.arrayBuffer());
86
- }
87
-
88
- /** @private */
89
- export let _loadBinaryFile: (
90
- indexURL: string,
91
- path: string
92
- ) => Promise<Uint8Array>;
93
- if (IN_NODE) {
94
- _loadBinaryFile = node_loadBinaryFile;
95
- } else {
96
- _loadBinaryFile = browser_loadBinaryFile;
97
- }
98
-
99
- /**
100
- * Currently loadScript is only used once to load `pyodide.asm.js`.
101
- * @param url
102
- * @async
103
- * @private
104
- */
105
- export let loadScript: (url: string) => Promise<void>;
106
-
107
- if (globalThis.document) {
108
- // browser
109
- loadScript = async (url) => await import(/* webpackIgnore: true */ url);
110
- } else if (globalThis.importScripts) {
111
- // webworker
112
- loadScript = async (url) => {
113
- // This is async only for consistency
114
- try {
115
- // use importScripts in classic web worker
116
- globalThis.importScripts(url);
117
- } catch (e) {
118
- // importScripts throws TypeError in a module type web worker, use import instead
119
- if (e instanceof TypeError) {
120
- await import(url);
121
- } else {
122
- throw e;
123
- }
124
- }
125
- };
126
- } else if (IN_NODE) {
127
- loadScript = nodeLoadScript;
128
- } else {
129
- throw new Error("Cannot determine runtime environment");
130
- }
131
-
132
- /**
133
- * Load a text file and executes it as Javascript
134
- * @param url The path to load. May be a url or a relative file system path.
135
- * @private
136
- */
137
- async function nodeLoadScript(url: string) {
138
- if (url.includes("://")) {
139
- // If it's a url, load it with fetch then eval it.
140
- nodeVmMod.runInThisContext(await (await nodeFetch(url)).text());
141
- } else {
142
- // Otherwise, hopefully it is a relative path we can load from the file
143
- // system.
144
- await import(nodePathMod.resolve(url));
145
- }
146
- }