pyodide.d.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. // Generated by dts-bundle-generator v8.1.1
  2. /**
  3. *
  4. * The Pyodide version.
  5. *
  6. * The version here is a Python version, following :pep:`440`. This is different
  7. * from the version in ``package.json`` which follows the node package manager
  8. * version convention.
  9. */
  10. export declare const version: string;
  11. /** @deprecated Use `import type { PyProxy } from "pyodide/ffi"` instead */
  12. interface PyProxy {
  13. [x: string]: any;
  14. }
  15. declare class PyProxy {
  16. /** @private */
  17. $$flags: number;
  18. /** @private */
  19. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  20. /**
  21. * @hideconstructor
  22. */
  23. constructor();
  24. /** @hidden */
  25. get [Symbol.toStringTag](): string;
  26. /**
  27. * The name of the type of the object.
  28. *
  29. * Usually the value is ``"module.name"`` but for builtins or
  30. * interpreter-defined types it is just ``"name"``. As pseudocode this is:
  31. *
  32. * .. code-block:: python
  33. *
  34. * ty = type(x)
  35. * if ty.__module__ == 'builtins' or ty.__module__ == "__main__":
  36. * return ty.__name__
  37. * else:
  38. * ty.__module__ + "." + ty.__name__
  39. *
  40. */
  41. get type(): string;
  42. /**
  43. * Returns `str(o)` (unless `pyproxyToStringRepr: true` was passed to
  44. * :js:func:`loadPyodide` in which case it will return `repr(o)`)
  45. */
  46. toString(): string;
  47. /**
  48. * Destroy the :js:class:`~pyodide.ffi.PyProxy`. This will release the memory. Any further attempt
  49. * to use the object will raise an error.
  50. *
  51. * In a browser supporting :js:data:`FinalizationRegistry`, Pyodide will
  52. * automatically destroy the :js:class:`~pyodide.ffi.PyProxy` when it is garbage collected, however
  53. * there is no guarantee that the finalizer will be run in a timely manner so
  54. * it is better to destroy the proxy explicitly.
  55. *
  56. * @param options
  57. * @param options.message The error message to print if use is attempted after
  58. * destroying. Defaults to "Object has already been destroyed".
  59. *
  60. */
  61. destroy(options?: {
  62. message?: string;
  63. destroyRoundtrip?: boolean;
  64. }): void;
  65. /**
  66. * Make a new :js:class:`~pyodide.ffi.PyProxy` pointing to the same Python object.
  67. * Useful if the :js:class:`~pyodide.ffi.PyProxy` is destroyed somewhere else.
  68. */
  69. copy(): PyProxy;
  70. /**
  71. * Converts the :js:class:`~pyodide.ffi.PyProxy` into a JavaScript object as best as possible. By
  72. * default does a deep conversion, if a shallow conversion is desired, you can
  73. * use ``proxy.toJs({depth : 1})``. See :ref:`Explicit Conversion of PyProxy
  74. * <type-translations-pyproxy-to-js>` for more info.
  75. * @param options
  76. * @return The JavaScript object resulting from the conversion.
  77. */
  78. toJs({ depth, pyproxies, create_pyproxies, dict_converter, default_converter, }?: {
  79. /** How many layers deep to perform the conversion. Defaults to infinite */
  80. depth?: number;
  81. /**
  82. * If provided, :js:meth:`toJs` will store all PyProxies created in this
  83. * list. This allows you to easily destroy all the PyProxies by iterating
  84. * the list without having to recurse over the generated structure. The most
  85. * common use case is to create a new empty list, pass the list as
  86. * ``pyproxies``, and then later iterate over ``pyproxies`` to destroy all of
  87. * created proxies.
  88. */
  89. pyproxies?: PyProxy[];
  90. /**
  91. * If false, :js:meth:`toJs` will throw a
  92. * :py:exc:`~pyodide.ffi.ConversionError` rather than producing a
  93. * :js:class:`~pyodide.ffi.PyProxy`.
  94. */
  95. create_pyproxies?: boolean;
  96. /**
  97. * A function to be called on an iterable of pairs ``[key, value]``. Convert
  98. * this iterable of pairs to the desired output. For instance,
  99. * :js:func:`Object.fromEntries` would convert the dict to an object,
  100. * :js:func:`Array.from` converts it to an :js:class:`Array` of pairs, and
  101. * ``(it) => new Map(it)`` converts it to a :js:class:`Map` (which is the
  102. * default behavior).
  103. */
  104. dict_converter?: (array: Iterable<[
  105. key: string,
  106. value: any
  107. ]>) => any;
  108. /**
  109. * Optional argument to convert objects with no default conversion. See the
  110. * documentation of :meth:`~pyodide.ffi.to_js`.
  111. */
  112. default_converter?: (obj: PyProxy, convert: (obj: PyProxy) => any, cacheConversion: (obj: PyProxy, result: any) => void) => any;
  113. }): any;
  114. }
  115. declare class PyProxyWithLength extends PyProxy {
  116. /** @private */
  117. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  118. }
  119. /** @deprecated Use `import type { PyProxyWithLength } from "pyodide/ffi"` instead */
  120. interface PyProxyWithLength extends PyLengthMethods {
  121. }
  122. declare class PyLengthMethods {
  123. /**
  124. * The length of the object.
  125. */
  126. get length(): number;
  127. }
  128. declare class PyProxyWithGet extends PyProxy {
  129. /** @private */
  130. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  131. }
  132. /** @deprecated Use `import type { PyProxyWithGet } from "pyodide/ffi"` instead */
  133. interface PyProxyWithGet extends PyGetItemMethods {
  134. }
  135. declare class PyGetItemMethods {
  136. /**
  137. * This translates to the Python code ``obj[key]``.
  138. *
  139. * @param key The key to look up.
  140. * @returns The corresponding value.
  141. */
  142. get(key: any): any;
  143. }
  144. declare class PyProxyWithSet extends PyProxy {
  145. /** @private */
  146. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  147. }
  148. /** @deprecated Use `import type { PyProxyWithSet } from "pyodide/ffi"` instead */
  149. interface PyProxyWithSet extends PySetItemMethods {
  150. }
  151. declare class PySetItemMethods {
  152. /**
  153. * This translates to the Python code ``obj[key] = value``.
  154. *
  155. * @param key The key to set.
  156. * @param value The value to set it to.
  157. */
  158. set(key: any, value: any): void;
  159. /**
  160. * This translates to the Python code ``del obj[key]``.
  161. *
  162. * @param key The key to delete.
  163. */
  164. delete(key: any): void;
  165. }
  166. declare class PyProxyWithHas extends PyProxy {
  167. /** @private */
  168. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  169. }
  170. /** @deprecated Use `import type { PyProxyWithHas } from "pyodide/ffi"` instead */
  171. interface PyProxyWithHas extends PyContainsMethods {
  172. }
  173. declare class PyContainsMethods {
  174. /**
  175. * This translates to the Python code ``key in obj``.
  176. *
  177. * @param key The key to check for.
  178. * @returns Is ``key`` present?
  179. */
  180. has(key: any): boolean;
  181. }
  182. declare class PyIterable extends PyProxy {
  183. /** @private */
  184. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  185. }
  186. /** @deprecated Use `import type { PyIterable } from "pyodide/ffi"` instead */
  187. interface PyIterable extends PyIterableMethods {
  188. }
  189. declare class PyIterableMethods {
  190. /**
  191. * This translates to the Python code ``iter(obj)``. Return an iterator
  192. * associated to the proxy. See the documentation for
  193. * :js:data:`Symbol.iterator`.
  194. *
  195. * This will be used implicitly by ``for(let x of proxy){}``.
  196. */
  197. [Symbol.iterator](): Iterator<any, any, any>;
  198. }
  199. declare class PyAsyncIterable extends PyProxy {
  200. /** @private */
  201. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  202. }
  203. /** @deprecated Use `import type { PyAsyncIterable } from "pyodide/ffi"` instead */
  204. interface PyAsyncIterable extends PyAsyncIterableMethods {
  205. }
  206. declare class PyAsyncIterableMethods {
  207. /**
  208. * This translates to the Python code ``aiter(obj)``. Return an async iterator
  209. * associated to the proxy. See the documentation for :js:data:`Symbol.asyncIterator`.
  210. *
  211. * This will be used implicitly by ``for(await let x of proxy){}``.
  212. */
  213. [Symbol.asyncIterator](): AsyncIterator<any, any, any>;
  214. }
  215. declare class PyIterator extends PyProxy {
  216. /** @private */
  217. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  218. }
  219. /** @deprecated Use `import type { PyIterator } from "pyodide/ffi"` instead */
  220. interface PyIterator extends PyIteratorMethods {
  221. }
  222. declare class PyIteratorMethods {
  223. /** @private */
  224. [Symbol.iterator](): this;
  225. /**
  226. * This translates to the Python code ``next(obj)``. Returns the next value of
  227. * the generator. See the documentation for :js:meth:`Generator.next` The
  228. * argument will be sent to the Python generator.
  229. *
  230. * This will be used implicitly by ``for(let x of proxy){}``.
  231. *
  232. * @param any The value to send to the generator. The value will be assigned
  233. * as a result of a yield expression.
  234. * @returns An Object with two properties: ``done`` and ``value``. When the
  235. * generator yields ``some_value``, ``next`` returns ``{done : false, value :
  236. * some_value}``. When the generator raises a :py:exc:`StopIteration`
  237. * exception, ``next`` returns ``{done : true, value : result_value}``.
  238. */
  239. next(arg?: any): IteratorResult<any, any>;
  240. }
  241. declare class PyGenerator extends PyProxy {
  242. /** @private */
  243. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  244. }
  245. /** @deprecated Use `import type { PyGenerator } from "pyodide/ffi"` instead */
  246. interface PyGenerator extends PyGeneratorMethods {
  247. }
  248. declare class PyGeneratorMethods {
  249. /**
  250. * Throws an exception into the Generator.
  251. *
  252. * See the documentation for :js:meth:`Generator.throw`.
  253. *
  254. * @param exception Error The error to throw into the generator. Must be an
  255. * instanceof ``Error``.
  256. * @returns An Object with two properties: ``done`` and ``value``. When the
  257. * generator yields ``some_value``, ``return`` returns ``{done : false, value
  258. * : some_value}``. When the generator raises a
  259. * ``StopIteration(result_value)`` exception, ``return`` returns ``{done :
  260. * true, value : result_value}``.
  261. */
  262. throw(exc: any): IteratorResult<any, any>;
  263. /**
  264. * Throws a :py:exc:`GeneratorExit` into the generator and if the
  265. * :py:exc:`GeneratorExit` is not caught returns the argument value ``{done:
  266. * true, value: v}``. If the generator catches the :py:exc:`GeneratorExit` and
  267. * returns or yields another value the next value of the generator this is
  268. * returned in the normal way. If it throws some error other than
  269. * :py:exc:`GeneratorExit` or :py:exc:`StopIteration`, that error is propagated. See
  270. * the documentation for :js:meth:`Generator.return`.
  271. *
  272. * @param any The value to return from the generator.
  273. * @returns An Object with two properties: ``done`` and ``value``. When the
  274. * generator yields ``some_value``, ``return`` returns ``{done : false, value
  275. * : some_value}``. When the generator raises a
  276. * ``StopIteration(result_value)`` exception, ``return`` returns ``{done :
  277. * true, value : result_value}``.
  278. */
  279. return(v: any): IteratorResult<any, any>;
  280. }
  281. declare class PyAsyncIterator extends PyProxy {
  282. /** @private */
  283. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  284. }
  285. /** @deprecated Use `import type { PyAsyncIterator } from "pyodide/ffi"` instead */
  286. interface PyAsyncIterator extends PyAsyncIteratorMethods {
  287. }
  288. declare class PyAsyncIteratorMethods {
  289. /** @private */
  290. [Symbol.asyncIterator](): this;
  291. /**
  292. * This translates to the Python code ``anext(obj)``. Returns the next value
  293. * of the asynchronous iterator. The argument will be sent to the Python
  294. * iterator (if it's a generator for instance).
  295. *
  296. * This will be used implicitly by ``for(let x of proxy){}``.
  297. *
  298. * @param any The value to send to a generator. The value will be assigned as
  299. * a result of a yield expression.
  300. * @returns An Object with two properties: ``done`` and ``value``. When the
  301. * iterator yields ``some_value``, ``next`` returns ``{done : false, value :
  302. * some_value}``. When the giterator is done, ``next`` returns
  303. * ``{done : true }``.
  304. */
  305. next(arg?: any): Promise<IteratorResult<any, any>>;
  306. }
  307. declare class PyAsyncGenerator extends PyProxy {
  308. /** @private */
  309. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  310. }
  311. /** @deprecated Use `import type { PyAsyncGenerator } from "pyodide/ffi"` instead */
  312. interface PyAsyncGenerator extends PyAsyncGeneratorMethods {
  313. }
  314. declare class PyAsyncGeneratorMethods {
  315. /**
  316. * Throws an exception into the Generator.
  317. *
  318. * See the documentation for :js:meth:`AsyncGenerator.throw`.
  319. *
  320. * @param exception Error The error to throw into the generator. Must be an
  321. * instanceof ``Error``.
  322. * @returns An Object with two properties: ``done`` and ``value``. When the
  323. * generator yields ``some_value``, ``return`` returns ``{done : false, value
  324. * : some_value}``. When the generator raises a
  325. * ``StopIteration(result_value)`` exception, ``return`` returns ``{done :
  326. * true, value : result_value}``.
  327. */
  328. throw(exc: any): Promise<IteratorResult<any, any>>;
  329. /**
  330. * Throws a :py:exc:`GeneratorExit` into the generator and if the
  331. * :py:exc:`GeneratorExit` is not caught returns the argument value ``{done:
  332. * true, value: v}``. If the generator catches the :py:exc:`GeneratorExit` and
  333. * returns or yields another value the next value of the generator this is
  334. * returned in the normal way. If it throws some error other than
  335. * :py:exc:`GeneratorExit` or :py:exc:`StopAsyncIteration`, that error is
  336. * propagated. See the documentation for :js:meth:`AsyncGenerator.throw`
  337. *
  338. * @param any The value to return from the generator.
  339. * @returns An Object with two properties: ``done`` and ``value``. When the
  340. * generator yields ``some_value``, ``return`` returns ``{done : false, value
  341. * : some_value}``. When the generator raises a :py:exc:`StopAsyncIteration`
  342. * exception, ``return`` returns ``{done : true, value : result_value}``.
  343. */
  344. return(v: any): Promise<IteratorResult<any, any>>;
  345. }
  346. declare class PySequence extends PyProxy {
  347. /** @private */
  348. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  349. }
  350. /** @deprecated Use `import type { PySequence } from "pyodide/ffi"` instead */
  351. interface PySequence extends PySequenceMethods {
  352. }
  353. declare class PySequenceMethods {
  354. /** @hidden */
  355. get [Symbol.isConcatSpreadable](): boolean;
  356. /**
  357. * See :js:meth:`Array.join`. The :js:meth:`Array.join` method creates and
  358. * returns a new string by concatenating all of the elements in the
  359. * :py:class:`~collections.abc.Sequence`.
  360. *
  361. * @param separator A string to separate each pair of adjacent elements of the
  362. * Sequence.
  363. *
  364. * @returns A string with all Sequence elements joined.
  365. */
  366. join(separator?: string): string;
  367. /**
  368. * See :js:meth:`Array.slice`. The :js:meth:`Array.slice` method returns a
  369. * shallow copy of a portion of a :py:class:`~collections.abc.Sequence` into a
  370. * new array object selected from ``start`` to ``stop`` (`stop` not included)
  371. * @param start Zero-based index at which to start extraction. Negative index
  372. * counts back from the end of the Sequence.
  373. * @param stop Zero-based index at which to end extraction. Negative index
  374. * counts back from the end of the Sequence.
  375. * @returns A new array containing the extracted elements.
  376. */
  377. slice(start?: number, stop?: number): any;
  378. /**
  379. * See :js:meth:`Array.lastIndexOf`. Returns the last index at which a given
  380. * element can be found in the Sequence, or -1 if it is not present.
  381. * @param elt Element to locate in the Sequence.
  382. * @param fromIndex Zero-based index at which to start searching backwards,
  383. * converted to an integer. Negative index counts back from the end of the
  384. * Sequence.
  385. * @returns The last index of the element in the Sequence; -1 if not found.
  386. */
  387. lastIndexOf(elt: any, fromIndex?: number): number;
  388. /**
  389. * See :js:meth:`Array.indexOf`. Returns the first index at which a given
  390. * element can be found in the Sequence, or -1 if it is not present.
  391. * @param elt Element to locate in the Sequence.
  392. * @param fromIndex Zero-based index at which to start searching, converted to
  393. * an integer. Negative index counts back from the end of the Sequence.
  394. * @returns The first index of the element in the Sequence; -1 if not found.
  395. */
  396. indexOf(elt: any, fromIndex?: number): number;
  397. /**
  398. * See :js:meth:`Array.forEach`. Executes a provided function once for each
  399. * ``Sequence`` element.
  400. * @param callbackfn A function to execute for each element in the ``Sequence``. Its
  401. * return value is discarded.
  402. * @param thisArg A value to use as ``this`` when executing ``callbackFn``.
  403. */
  404. forEach(callbackfn: (elt: any) => void, thisArg?: any): void;
  405. /**
  406. * See :js:meth:`Array.map`. Creates a new array populated with the results of
  407. * calling a provided function on every element in the calling ``Sequence``.
  408. * @param callbackfn A function to execute for each element in the ``Sequence``. Its
  409. * return value is added as a single element in the new array.
  410. * @param thisArg A value to use as ``this`` when executing ``callbackFn``.
  411. */
  412. map<U>(callbackfn: (elt: any, index: number, array: any) => U, thisArg?: any): U[];
  413. /**
  414. * See :js:meth:`Array.filter`. Creates a shallow copy of a portion of a given
  415. * ``Sequence``, filtered down to just the elements from the given array that pass
  416. * the test implemented by the provided function.
  417. * @param callbackfn A function to execute for each element in the array. It
  418. * should return a truthy value to keep the element in the resulting array,
  419. * and a falsy value otherwise.
  420. * @param thisArg A value to use as ``this`` when executing ``predicate``.
  421. */
  422. filter(predicate: (elt: any, index: number, array: any) => boolean, thisArg?: any): any[];
  423. /**
  424. * See :js:meth:`Array.some`. Tests whether at least one element in the
  425. * ``Sequence`` passes the test implemented by the provided function.
  426. * @param callbackfn A function to execute for each element in the
  427. * ``Sequence``. It should return a truthy value to indicate the element
  428. * passes the test, and a falsy value otherwise.
  429. * @param thisArg A value to use as ``this`` when executing ``predicate``.
  430. */
  431. some(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean;
  432. /**
  433. * See :js:meth:`Array.every`. Tests whether every element in the ``Sequence``
  434. * passes the test implemented by the provided function.
  435. * @param callbackfn A function to execute for each element in the
  436. * ``Sequence``. It should return a truthy value to indicate the element
  437. * passes the test, and a falsy value otherwise.
  438. * @param thisArg A value to use as ``this`` when executing ``predicate``.
  439. */
  440. every(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean;
  441. /**
  442. * See :js:meth:`Array.reduce`. Executes a user-supplied "reducer" callback
  443. * function on each element of the Sequence, in order, passing in the return
  444. * value from the calculation on the preceding element. The final result of
  445. * running the reducer across all elements of the Sequence is a single value.
  446. * @param callbackfn A function to execute for each element in the ``Sequence``. Its
  447. * return value is discarded.
  448. * @param thisArg A value to use as ``this`` when executing ``callbackfn``.
  449. */
  450. reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any) => any, initialValue?: any): any;
  451. /**
  452. * See :js:meth:`Array.reduceRight`. Applies a function against an accumulator
  453. * and each value of the Sequence (from right to left) to reduce it to a
  454. * single value.
  455. * @param callbackfn A function to execute for each element in the Sequence.
  456. * Its return value is discarded.
  457. * @param thisArg A value to use as ``this`` when executing ``callbackFn``.
  458. */
  459. reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any) => any, initialValue: any): any;
  460. /**
  461. * See :js:meth:`Array.at`. Takes an integer value and returns the item at
  462. * that index.
  463. * @param index Zero-based index of the Sequence element to be returned,
  464. * converted to an integer. Negative index counts back from the end of the
  465. * Sequence.
  466. * @returns The element in the Sequence matching the given index.
  467. */
  468. at(index: number): any;
  469. /**
  470. * The :js:meth:`Array.concat` method is used to merge two or more arrays.
  471. * This method does not change the existing arrays, but instead returns a new
  472. * array.
  473. * @param rest Arrays and/or values to concatenate into a new array.
  474. * @returns A new Array instance.
  475. */
  476. concat(...rest: ConcatArray<any>[]): any[];
  477. /**
  478. * The :js:meth:`Array.includes` method determines whether a Sequence
  479. * includes a certain value among its entries, returning true or false as
  480. * appropriate.
  481. * @param elt
  482. * @returns
  483. */
  484. includes(elt: any): any;
  485. /**
  486. * The :js:meth:`Array.entries` method returns a new iterator object that
  487. * contains the key/value pairs for each index in the ``Sequence``.
  488. * @returns A new iterator object.
  489. */
  490. entries(): IterableIterator<[
  491. number,
  492. any
  493. ]>;
  494. /**
  495. * The :js:meth:`Array.keys` method returns a new iterator object that
  496. * contains the keys for each index in the ``Sequence``.
  497. * @returns A new iterator object.
  498. */
  499. keys(): IterableIterator<number>;
  500. /**
  501. * The :js:meth:`Array.values` method returns a new iterator object that
  502. * contains the values for each index in the ``Sequence``.
  503. * @returns A new iterator object.
  504. */
  505. values(): IterableIterator<any>;
  506. /**
  507. * The :js:meth:`Array.find` method returns the first element in the provided
  508. * array that satisfies the provided testing function.
  509. * @param predicate A function to execute for each element in the
  510. * ``Sequence``. It should return a truthy value to indicate a matching
  511. * element has been found, and a falsy value otherwise.
  512. * @param thisArg A value to use as ``this`` when executing ``predicate``.
  513. * @returns The first element in the ``Sequence`` that satisfies the provided
  514. * testing function.
  515. */
  516. find(predicate: (value: any, index: number, obj: any[]) => any, thisArg?: any): any;
  517. /**
  518. * The :js:meth:`Array.findIndex` method returns the index of the first
  519. * element in the provided array that satisfies the provided testing function.
  520. * @param predicate A function to execute for each element in the
  521. * ``Sequence``. It should return a truthy value to indicate a matching
  522. * element has been found, and a falsy value otherwise.
  523. * @param thisArg A value to use as ``this`` when executing ``predicate``.
  524. * @returns The index of the first element in the ``Sequence`` that satisfies
  525. * the provided testing function.
  526. */
  527. findIndex(predicate: (value: any, index: number, obj: any[]) => any, thisArg?: any): number;
  528. }
  529. declare class PyMutableSequence extends PyProxy {
  530. /** @private */
  531. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  532. }
  533. /** @deprecated Use `import type { PyMutableSequence } from "pyodide/ffi"` instead */
  534. interface PyMutableSequence extends PyMutableSequenceMethods {
  535. }
  536. declare class PyMutableSequenceMethods {
  537. /**
  538. * The :js:meth:`Array.reverse` method reverses a :js:class:`PyMutableSequence` in
  539. * place.
  540. * @returns A reference to the same :js:class:`PyMutableSequence`
  541. */
  542. reverse(): PyMutableSequence;
  543. /**
  544. * The :js:meth:`Array.sort` method sorts the elements of a
  545. * :js:class:`PyMutableSequence` in place.
  546. * @param compareFn A function that defines the sort order.
  547. * @returns A reference to the same :js:class:`PyMutableSequence`
  548. */
  549. sort(compareFn?: (a: any, b: any) => number): PyMutableSequence;
  550. /**
  551. * The :js:meth:`Array.splice` method changes the contents of a
  552. * :js:class:`PyMutableSequence` by removing or replacing existing elements and/or
  553. * adding new elements in place.
  554. * @param start Zero-based index at which to start changing the
  555. * :js:class:`PyMutableSequence`.
  556. * @param deleteCount An integer indicating the number of elements in the
  557. * :js:class:`PyMutableSequence` to remove from ``start``.
  558. * @param items The elements to add to the :js:class:`PyMutableSequence`, beginning from
  559. * ``start``.
  560. * @returns An array containing the deleted elements.
  561. */
  562. splice(start: number, deleteCount?: number, ...items: any[]): any[];
  563. /**
  564. * The :js:meth:`Array.push` method adds the specified elements to the end of
  565. * a :js:class:`PyMutableSequence`.
  566. * @param elts The element(s) to add to the end of the :js:class:`PyMutableSequence`.
  567. * @returns The new length property of the object upon which the method was
  568. * called.
  569. */
  570. push(...elts: any[]): any;
  571. /**
  572. * The :js:meth:`Array.pop` method removes the last element from a
  573. * :js:class:`PyMutableSequence`.
  574. * @returns The removed element from the :js:class:`PyMutableSequence`; undefined if the
  575. * :js:class:`PyMutableSequence` is empty.
  576. */
  577. pop(): any;
  578. /**
  579. * The :js:meth:`Array.shift` method removes the first element from a
  580. * :js:class:`PyMutableSequence`.
  581. * @returns The removed element from the :js:class:`PyMutableSequence`; undefined if the
  582. * :js:class:`PyMutableSequence` is empty.
  583. */
  584. shift(): any;
  585. /**
  586. * The :js:meth:`Array.unshift` method adds the specified elements to the
  587. * beginning of a :js:class:`PyMutableSequence`.
  588. * @param elts The elements to add to the front of the :js:class:`PyMutableSequence`.
  589. * @returns The new length of the :js:class:`PyMutableSequence`.
  590. */
  591. unshift(...elts: any[]): any;
  592. /**
  593. * The :js:meth:`Array.copyWithin` method shallow copies part of a
  594. * :js:class:`PyMutableSequence` to another location in the same :js:class:`PyMutableSequence`
  595. * without modifying its length.
  596. * @param target Zero-based index at which to copy the sequence to.
  597. * @param start Zero-based index at which to start copying elements from.
  598. * @param end Zero-based index at which to end copying elements from.
  599. * @returns The modified :js:class:`PyMutableSequence`.
  600. */
  601. copyWithin(target: number, start?: number, end?: number): any;
  602. /**
  603. * The :js:meth:`Array.fill` method changes all elements in an array to a
  604. * static value, from a start index to an end index.
  605. * @param value Value to fill the array with.
  606. * @param start Zero-based index at which to start filling. Default 0.
  607. * @param end Zero-based index at which to end filling. Default
  608. * ``list.length``.
  609. * @returns
  610. */
  611. fill(value: any, start?: number, end?: number): any;
  612. }
  613. declare class PyAwaitable extends PyProxy {
  614. /** @private */
  615. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  616. }
  617. /** @deprecated Use `import type { PyAwaitable } from "pyodide/ffi"` instead */
  618. interface PyAwaitable extends Promise<any> {
  619. }
  620. declare class PyCallable extends PyProxy {
  621. /** @private */
  622. static [Symbol.hasInstance](obj: any): obj is PyCallable;
  623. }
  624. /** @deprecated Use `import type { PyCallable } from "pyodide/ffi"` instead */
  625. interface PyCallable extends PyCallableMethods {
  626. (...args: any[]): any;
  627. }
  628. declare class PyCallableMethods {
  629. /**
  630. * The ``apply()`` method calls the specified function with a given this
  631. * value, and arguments provided as an array (or an array-like object). Like
  632. * :js:meth:`Function.apply`.
  633. *
  634. * @param thisArg The ``this`` argument. Has no effect unless the
  635. * :js:class:`~pyodide.ffi.PyCallable` has :js:meth:`captureThis` set. If
  636. * :js:meth:`captureThis` is set, it will be passed as the first argument to
  637. * the Python function.
  638. * @param jsargs The array of arguments
  639. * @returns The result from the function call.
  640. */
  641. apply(thisArg: any, jsargs: any): any;
  642. /**
  643. * Calls the function with a given this value and arguments provided
  644. * individually. See :js:meth:`Function.call`.
  645. *
  646. * @param thisArg The ``this`` argument. Has no effect unless the
  647. * :js:class:`~pyodide.ffi.PyCallable` has :js:meth:`captureThis` set. If
  648. * :js:meth:`captureThis` is set, it will be passed as the first argument to
  649. * the Python function.
  650. * @param jsargs The arguments
  651. * @returns The result from the function call.
  652. */
  653. call(thisArg: any, ...jsargs: any): any;
  654. /**
  655. * Call the function with keyword arguments. The last argument must be an
  656. * object with the keyword arguments.
  657. */
  658. callKwargs(...jsargs: any): any;
  659. /**
  660. * Call the function in a "relaxed" manner. Any extra arguments will be
  661. * ignored. This matches the behavior of JavaScript functions more accurately.
  662. *
  663. * Any extra arguments will be ignored. This matches the behavior of
  664. * JavaScript functions more accurately. Missing arguments are **NOT** filled
  665. * with `None`. If too few arguments are passed, this will still raise a
  666. * TypeError.
  667. *
  668. * This uses :py:func:`pyodide.code.relaxed_call`.
  669. */
  670. callRelaxed(...jsargs: any): any;
  671. /**
  672. * Call the function with keyword arguments in a "relaxed" manner. The last
  673. * argument must be an object with the keyword arguments. Any extra arguments
  674. * will be ignored. This matches the behavior of JavaScript functions more
  675. * accurately.
  676. *
  677. * Missing arguments are **NOT** filled with `None`. If too few arguments are
  678. * passed, this will still raise a TypeError. Also, if the same argument is
  679. * passed as both a keyword argument and a positional argument, it will raise
  680. * an error.
  681. *
  682. * This uses :py:func:`pyodide.code.relaxed_call`.
  683. */
  684. callKwargsRelaxed(...jsargs: any): any;
  685. /**
  686. * Call the function with stack switching enabled. Functions called this way
  687. * can use
  688. * :py:meth:`PyodideFuture.syncify() <pyodide.webloop.PyodideFuture.syncify>`
  689. * to block until a :py:class:`~asyncio.Future` or :js:class:`Promise` is
  690. * resolved. Only works in runtimes with JS Promise integration.
  691. *
  692. * .. admonition:: Experimental
  693. * :class: warning
  694. *
  695. * This feature is not yet stable.
  696. *
  697. * @experimental
  698. */
  699. callSyncifying(...jsargs: any): Promise<any>;
  700. /**
  701. * Call the function with stack switching enabled. The last argument must be
  702. * an object with the keyword arguments. Functions called this way can use
  703. * :py:meth:`PyodideFuture.syncify() <pyodide.webloop.PyodideFuture.syncify>`
  704. * to block until a :py:class:`~asyncio.Future` or :js:class:`Promise` is
  705. * resolved. Only works in runtimes with JS Promise integration.
  706. *
  707. * .. admonition:: Experimental
  708. * :class: warning
  709. *
  710. * This feature is not yet stable.
  711. *
  712. * @experimental
  713. */
  714. callSyncifyingKwargs(...jsargs: any): Promise<any>;
  715. /**
  716. * The ``bind()`` method creates a new function that, when called, has its
  717. * ``this`` keyword set to the provided value, with a given sequence of
  718. * arguments preceding any provided when the new function is called. See
  719. * :js:meth:`Function.bind`.
  720. *
  721. * If the :js:class:`~pyodide.ffi.PyCallable` does not have
  722. * :js:meth:`captureThis` set, the ``this`` parameter will be discarded. If it
  723. * does have :js:meth:`captureThis` set, ``thisArg`` will be set to the first
  724. * argument of the Python function. The returned proxy and the original proxy
  725. * have the same lifetime so destroying either destroys both.
  726. *
  727. * @param thisArg The value to be passed as the ``this`` parameter to the
  728. * target function ``func`` when the bound function is called.
  729. * @param jsargs Extra arguments to prepend to arguments provided to the bound
  730. * function when invoking ``func``.
  731. * @returns
  732. */
  733. bind(thisArg: any, ...jsargs: any): PyProxy;
  734. /**
  735. * Returns a :js:class:`~pyodide.ffi.PyProxy` that passes ``this`` as the first argument to the
  736. * Python function. The returned :js:class:`~pyodide.ffi.PyProxy` has the internal ``captureThis``
  737. * property set.
  738. *
  739. * It can then be used as a method on a JavaScript object. The returned proxy
  740. * and the original proxy have the same lifetime so destroying either destroys
  741. * both.
  742. *
  743. * For example:
  744. *
  745. * .. code-block:: pyodide
  746. *
  747. * let obj = { a : 7 };
  748. * pyodide.runPython(`
  749. * def f(self):
  750. * return self.a
  751. * `);
  752. * // Without captureThis, it doesn't work to use f as a method for obj:
  753. * obj.f = pyodide.globals.get("f");
  754. * obj.f(); // raises "TypeError: f() missing 1 required positional argument: 'self'"
  755. * // With captureThis, it works fine:
  756. * obj.f = pyodide.globals.get("f").captureThis();
  757. * obj.f(); // returns 7
  758. *
  759. * @returns The resulting :js:class:`~pyodide.ffi.PyProxy`. It has the same lifetime as the
  760. * original :js:class:`~pyodide.ffi.PyProxy` but passes ``this`` to the wrapped function.
  761. *
  762. */
  763. captureThis(): PyProxy;
  764. }
  765. declare class PyBuffer extends PyProxy {
  766. /** @private */
  767. static [Symbol.hasInstance](obj: any): obj is PyBuffer;
  768. }
  769. /** @deprecated Use `import type { PyBuffer } from "pyodide/ffi"` instead */
  770. interface PyBuffer extends PyBufferMethods {
  771. }
  772. declare class PyBufferMethods {
  773. /**
  774. * Get a view of the buffer data which is usable from JavaScript. No copy is
  775. * ever performed.
  776. *
  777. * We do not support suboffsets, if the buffer requires suboffsets we will
  778. * throw an error. JavaScript nd array libraries can't handle suboffsets
  779. * anyways. In this case, you should use the :js:meth:`~PyProxy.toJs` api or
  780. * copy the buffer to one that doesn't use suboffsets (using e.g.,
  781. * :py:func:`numpy.ascontiguousarray`).
  782. *
  783. * If the buffer stores big endian data or half floats, this function will
  784. * fail without an explicit type argument. For big endian data you can use
  785. * :js:meth:`~PyProxy.toJs`. :js:class:`DataView` has support for big endian
  786. * data, so you might want to pass ``'dataview'`` as the type argument in that
  787. * case.
  788. *
  789. * @param type The type of the :js:attr:`~pyodide.ffi.PyBufferView.data` field
  790. * in the output. Should be one of: ``"i8"``, ``"u8"``, ``"u8clamped"``,
  791. * ``"i16"``, ``"u16"``, ``"i32"``, ``"u32"``, ``"i32"``, ``"u32"``,
  792. * ``"i64"``, ``"u64"``, ``"f32"``, ``"f64``, or ``"dataview"``. This argument
  793. * is optional, if absent :js:meth:`~pyodide.ffi.PyBuffer.getBuffer` will try
  794. * to determine the appropriate output type based on the buffer format string
  795. * (see :std:ref:`struct-format-strings`).
  796. */
  797. getBuffer(type?: string): PyBufferView;
  798. }
  799. declare class PyDict extends PyProxy {
  800. /** @private */
  801. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  802. }
  803. /** @deprecated Use `import type { PyDict } from "pyodide/ffi"` instead */
  804. interface PyDict extends PyProxyWithGet, PyProxyWithSet, PyProxyWithHas, PyProxyWithLength, PyIterable {
  805. }
  806. /** @deprecated Use `import type { PyBufferView } from "pyodide/ffi"` instead */
  807. declare class PyBufferView {
  808. /**
  809. * The offset of the first entry of the array. For instance if our array
  810. * is 3d, then you will find ``array[0,0,0]`` at
  811. * ``pybuf.data[pybuf.offset]``
  812. */
  813. offset: number;
  814. /**
  815. * If the data is read only, you should not modify it. There is no way for us
  816. * to enforce this, but it may cause very weird behavior. See
  817. * :py:attr:`memoryview.readonly`.
  818. */
  819. readonly: boolean;
  820. /**
  821. * The format string for the buffer. See :ref:`struct-format-strings`
  822. * and :py:attr:`memoryview.format`.
  823. */
  824. format: string;
  825. /**
  826. * How large is each entry in bytes? See :py:attr:`memoryview.itemsize`.
  827. */
  828. itemsize: number;
  829. /**
  830. * The number of dimensions of the buffer. If ``ndim`` is 0, the buffer
  831. * represents a single scalar or struct. Otherwise, it represents an
  832. * array. See :py:attr:`memoryview.ndim`.
  833. */
  834. ndim: number;
  835. /**
  836. * The total number of bytes the buffer takes up. This is equal to
  837. * :js:attr:`buff.data.byteLength <TypedArray.byteLength>`. See :py:attr:`memoryview.nbytes`.
  838. */
  839. nbytes: number;
  840. /**
  841. * The shape of the buffer, that is how long it is in each dimension.
  842. * The length will be equal to ``ndim``. For instance, a 2x3x4 array
  843. * would have shape ``[2, 3, 4]``. See :py:attr:`memoryview.shape`.
  844. */
  845. shape: number[];
  846. /**
  847. * An array of of length ``ndim`` giving the number of elements to skip
  848. * to get to a new element in each dimension. See the example definition
  849. * of a ``multiIndexToIndex`` function above. See :py:attr:`memoryview.strides`.
  850. */
  851. strides: number[];
  852. /**
  853. * The actual data. A typed array of an appropriate size backed by a segment
  854. * of the WASM memory.
  855. *
  856. * The ``type`` argument of :js:meth:`~pyodide.ffi.PyBuffer.getBuffer` determines
  857. * which sort of :js:class:`TypedArray` or :js:class:`DataView` to return. By
  858. * default :js:meth:`~pyodide.ffi.PyBuffer.getBuffer` will look at the format string
  859. * to determine the most appropriate option. Most often the result is a
  860. * :js:class:`Uint8Array`.
  861. *
  862. * .. admonition:: Contiguity
  863. * :class: warning
  864. *
  865. * If the buffer is not contiguous, the :js:attr:`~PyBufferView.readonly`
  866. * TypedArray will contain data that is not part of the buffer. Modifying
  867. * this data leads to undefined behavior.
  868. *
  869. * .. admonition:: Read only buffers
  870. * :class: warning
  871. *
  872. * If :js:attr:`buffer.readonly <PyBufferView.readonly>` is ``true``, you
  873. * should not modify the buffer. Modifying a read only buffer leads to
  874. * undefined behavior.
  875. *
  876. */
  877. data: TypedArray;
  878. /**
  879. * Is it C contiguous? See :py:attr:`memoryview.c_contiguous`.
  880. */
  881. c_contiguous: boolean;
  882. /**
  883. * Is it Fortran contiguous? See :py:attr:`memoryview.f_contiguous`.
  884. */
  885. f_contiguous: boolean;
  886. _released: boolean;
  887. _view_ptr: number;
  888. /** @private */
  889. constructor();
  890. /**
  891. * Release the buffer. This allows the memory to be reclaimed.
  892. */
  893. release(): void;
  894. }
  895. type InFuncType = () => null | undefined | string | ArrayBuffer | Uint8Array | number;
  896. declare function setStdin(options?: {
  897. stdin?: InFuncType;
  898. read?: (buffer: Uint8Array) => number;
  899. error?: boolean;
  900. isatty?: boolean;
  901. autoEOF?: boolean;
  902. }): void;
  903. declare function setStdout(options?: {
  904. batched?: (output: string) => void;
  905. raw?: (charCode: number) => void;
  906. write?: (buffer: Uint8Array) => number;
  907. isatty?: boolean;
  908. }): void;
  909. declare function setStderr(options?: {
  910. batched?: (output: string) => void;
  911. raw?: (charCode: number) => void;
  912. write?: (buffer: Uint8Array) => number;
  913. isatty?: boolean;
  914. }): void;
  915. type PackageType = "package" | "cpython_module" | "shared_library" | "static_library";
  916. export type PackageData = {
  917. name: string;
  918. version: string;
  919. fileName: string;
  920. /** @experimental */
  921. packageType: PackageType;
  922. };
  923. declare function loadPackage(names: string | PyProxy | Array<string>, options?: {
  924. messageCallback?: (message: string) => void;
  925. errorCallback?: (message: string) => void;
  926. checkIntegrity?: boolean;
  927. }): Promise<Array<PackageData>>;
  928. /** @deprecated Use `import type { TypedArray } from "pyodide/ffi"` instead */
  929. export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array;
  930. interface CanvasInterface {
  931. setCanvas2D(canvas: HTMLCanvasElement): void;
  932. getCanvas2D(): HTMLCanvasElement | undefined;
  933. setCanvas3D(canvas: HTMLCanvasElement): void;
  934. getCanvas3D(): HTMLCanvasElement | undefined;
  935. }
  936. declare class PythonError extends Error {
  937. /**
  938. * The address of the error we are wrapping. We may later compare this
  939. * against sys.last_exc.
  940. * WARNING: we don't own a reference to this pointer, dereferencing it
  941. * may be a use-after-free error!
  942. * @private
  943. */
  944. __error_address: number;
  945. /**
  946. * The name of the Python error class, e.g, :py:exc:`RuntimeError` or
  947. * :py:exc:`KeyError`.
  948. */
  949. type: string;
  950. constructor(type: string, message: string, error_address: number);
  951. }
  952. type NativeFS = {
  953. syncfs: () => Promise<void>;
  954. };
  955. declare class PyodideAPI {
  956. /** @hidden */
  957. static version: string;
  958. /** @hidden */
  959. static loadPackage: typeof loadPackage;
  960. /** @hidden */
  961. static loadedPackages: {
  962. [key: string]: string;
  963. };
  964. /** @hidden */
  965. static ffi: {
  966. PyProxy: typeof PyProxy;
  967. PyProxyWithLength: typeof PyProxyWithLength;
  968. PyProxyWithGet: typeof PyProxyWithGet;
  969. PyProxyWithSet: typeof PyProxyWithSet;
  970. PyProxyWithHas: typeof PyProxyWithHas;
  971. PyDict: typeof PyDict;
  972. PyIterable: typeof PyIterable;
  973. PyAsyncIterable: typeof PyAsyncIterable;
  974. PyIterator: typeof PyIterator;
  975. PyAsyncIterator: typeof PyAsyncIterator;
  976. PyGenerator: typeof PyGenerator;
  977. PyAsyncGenerator: typeof PyAsyncGenerator;
  978. PyAwaitable: typeof PyAwaitable;
  979. PyCallable: typeof PyCallable;
  980. PyBuffer: typeof PyBuffer;
  981. PyBufferView: typeof PyBufferView;
  982. PythonError: typeof PythonError;
  983. PySequence: typeof PySequence;
  984. PyMutableSequence: typeof PyMutableSequence;
  985. };
  986. /** @hidden */
  987. static setStdin: typeof setStdin;
  988. /** @hidden */
  989. static setStdout: typeof setStdout;
  990. /** @hidden */
  991. static setStderr: typeof setStderr;
  992. /**
  993. *
  994. * An alias to the global Python namespace.
  995. *
  996. * For example, to access a variable called ``foo`` in the Python global
  997. * scope, use ``pyodide.globals.get("foo")``
  998. */
  999. static globals: PyProxy;
  1000. /**
  1001. * An alias to the `Emscripten File System API
  1002. * <https://emscripten.org/docs/api_reference/Filesystem-API.html>`_.
  1003. *
  1004. * This provides a wide range of POSIX-`like` file/device operations, including
  1005. * `mount
  1006. * <https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.mount>`_
  1007. * which can be used to extend the in-memory filesystem with features like `persistence
  1008. * <https://emscripten.org/docs/api_reference/Filesystem-API.html#persistent-data>`_.
  1009. *
  1010. * While all the file systems implementations are enabled, only the default
  1011. * ``MEMFS`` is guaranteed to work in all runtime settings. The implementations
  1012. * are available as members of ``FS.filesystems``:
  1013. * ``IDBFS``, ``NODEFS``, ``PROXYFS``, ``WORKERFS``.
  1014. */
  1015. static FS: any;
  1016. /**
  1017. * An alias to the `Emscripten Path API
  1018. * <https://github.com/emscripten-core/emscripten/blob/main/src/library_path.js>`_.
  1019. *
  1020. * This provides a variety of operations for working with file system paths, such as
  1021. * ``dirname``, ``normalize``, and ``splitPath``.
  1022. */
  1023. static PATH: any;
  1024. /**
  1025. * See :ref:`js-api-pyodide-canvas`.
  1026. * @hidetype
  1027. */
  1028. static canvas: CanvasInterface;
  1029. /**
  1030. * A map from posix error names to error codes.
  1031. */
  1032. static ERRNO_CODES: {
  1033. [code: string]: number;
  1034. };
  1035. /**
  1036. * An alias to the Python :ref:`pyodide <python-api>` package.
  1037. *
  1038. * You can use this to call functions defined in the Pyodide Python package
  1039. * from JavaScript.
  1040. */
  1041. static pyodide_py: PyProxy;
  1042. /**
  1043. * Inspect a Python code chunk and use :js:func:`pyodide.loadPackage` to install
  1044. * any known packages that the code chunk imports. Uses the Python API
  1045. * :func:`pyodide.code.find\_imports` to inspect the code.
  1046. *
  1047. * For example, given the following code as input
  1048. *
  1049. * .. code-block:: python
  1050. *
  1051. * import numpy as np
  1052. * x = np.array([1, 2, 3])
  1053. *
  1054. * :js:func:`loadPackagesFromImports` will call
  1055. * ``pyodide.loadPackage(['numpy'])``.
  1056. *
  1057. * @param code The code to inspect.
  1058. * @param options Options passed to :js:func:`pyodide.loadPackage`.
  1059. * @param options.messageCallback A callback, called with progress messages
  1060. * (optional)
  1061. * @param options.errorCallback A callback, called with error/warning messages
  1062. * (optional)
  1063. * @param options.checkIntegrity If true, check the integrity of the downloaded
  1064. * packages (default: true)
  1065. * @async
  1066. */
  1067. static loadPackagesFromImports(code: string, options?: {
  1068. messageCallback?: (message: string) => void;
  1069. errorCallback?: (message: string) => void;
  1070. checkIntegrity?: boolean;
  1071. }): Promise<Array<PackageData>>;
  1072. /**
  1073. * Runs a string of Python code from JavaScript, using :py:func:`~pyodide.code.eval_code`
  1074. * to evaluate the code. If the last statement in the Python code is an
  1075. * expression (and the code doesn't end with a semicolon), the value of the
  1076. * expression is returned.
  1077. *
  1078. * @param code The Python code to run
  1079. * @param options
  1080. * @param options.globals An optional Python dictionary to use as the globals.
  1081. * Defaults to :js:attr:`pyodide.globals`.
  1082. * @param options.locals An optional Python dictionary to use as the locals.
  1083. * Defaults to the same as ``globals``.
  1084. * @param options.filename An optional string to use as the file name.
  1085. * Defaults to ``"<exec>"``. If a custom file name is given, the
  1086. * traceback for any exception that is thrown will show source lines
  1087. * (unless the given file name starts with ``<`` and ends with ``>``).
  1088. * @returns The result of the Python code translated to JavaScript. See the
  1089. * documentation for :py:func:`~pyodide.code.eval_code` for more info.
  1090. * @example
  1091. * async function main(){
  1092. * const pyodide = await loadPyodide();
  1093. * console.log(pyodide.runPython("1 + 2"));
  1094. * // 3
  1095. *
  1096. * const globals = pyodide.toPy({ x: 3 });
  1097. * console.log(pyodide.runPython("x + 1", { globals }));
  1098. * // 4
  1099. *
  1100. * const locals = pyodide.toPy({ arr: [1, 2, 3] });
  1101. * console.log(pyodide.runPython("sum(arr)", { locals }));
  1102. * // 6
  1103. * }
  1104. * main();
  1105. */
  1106. static runPython(code: string, options?: {
  1107. globals?: PyProxy;
  1108. locals?: PyProxy;
  1109. filename?: string;
  1110. }): any;
  1111. /**
  1112. * Run a Python code string with top level await using
  1113. * :py:func:`~pyodide.code.eval_code_async` to evaluate the code. Returns a promise which
  1114. * resolves when execution completes. If the last statement in the Python code
  1115. * is an expression (and the code doesn't end with a semicolon), the returned
  1116. * promise will resolve to the value of this expression.
  1117. *
  1118. * For example:
  1119. *
  1120. * .. code-block:: pyodide
  1121. *
  1122. * let result = await pyodide.runPythonAsync(`
  1123. * from js import fetch
  1124. * response = await fetch("./pyodide-lock.json")
  1125. * packages = await response.json()
  1126. * # If final statement is an expression, its value is returned to JavaScript
  1127. * len(packages.packages.object_keys())
  1128. * `);
  1129. * console.log(result); // 79
  1130. *
  1131. * .. admonition:: Python imports
  1132. * :class: warning
  1133. *
  1134. * Since pyodide 0.18.0, you must call :js:func:`loadPackagesFromImports` to
  1135. * import any python packages referenced via ``import`` statements in your
  1136. * code. This function will no longer do it for you.
  1137. *
  1138. * @param code The Python code to run
  1139. * @param options
  1140. * @param options.globals An optional Python dictionary to use as the globals.
  1141. * Defaults to :js:attr:`pyodide.globals`.
  1142. * @param options.locals An optional Python dictionary to use as the locals.
  1143. * Defaults to the same as ``globals``.
  1144. * @param options.filename An optional string to use as the file name.
  1145. * Defaults to ``"<exec>"``. If a custom file name is given, the
  1146. * traceback for any exception that is thrown will show source lines
  1147. * (unless the given file name starts with ``<`` and ends with ``>``).
  1148. * @returns The result of the Python code translated to JavaScript.
  1149. * @async
  1150. */
  1151. static runPythonAsync(code: string, options?: {
  1152. globals?: PyProxy;
  1153. locals?: PyProxy;
  1154. filename?: string;
  1155. }): Promise<any>;
  1156. /**
  1157. * Registers the JavaScript object ``module`` as a JavaScript module named
  1158. * ``name``. This module can then be imported from Python using the standard
  1159. * Python import system. If another module by the same name has already been
  1160. * imported, this won't have much effect unless you also delete the imported
  1161. * module from :py:data:`sys.modules`. This calls
  1162. * :func:`~pyodide.ffi.register_js_module`.
  1163. *
  1164. * Any attributes of the JavaScript objects which are themselves objects will
  1165. * be treated as submodules:
  1166. * ```pyodide
  1167. * pyodide.registerJsModule("mymodule", { submodule: { value: 7 } });
  1168. * pyodide.runPython(`
  1169. * from mymodule.submodule import value
  1170. * assert value == 7
  1171. * `);
  1172. * ```
  1173. * If you wish to prevent this, try the following instead:
  1174. * ```pyodide
  1175. * const sys = pyodide.pyimport("sys");
  1176. * sys.modules.set("mymodule", { obj: { value: 7 } });
  1177. * pyodide.runPython(`
  1178. * from mymodule import obj
  1179. * assert obj.value == 7
  1180. * # attempting to treat obj as a submodule raises ModuleNotFoundError:
  1181. * # "No module named 'mymodule.obj'; 'mymodule' is not a package"
  1182. * from mymodule.obj import value
  1183. * `);
  1184. * ```
  1185. *
  1186. * @param name Name of the JavaScript module to add
  1187. * @param module JavaScript object backing the module
  1188. */
  1189. static registerJsModule(name: string, module: object): void;
  1190. /**
  1191. * Unregisters a JavaScript module with given name that has been previously
  1192. * registered with :js:func:`pyodide.registerJsModule` or
  1193. * :func:`~pyodide.ffi.register_js_module`. If a JavaScript module with that
  1194. * name does not already exist, will throw an error. Note that if the module has
  1195. * already been imported, this won't have much effect unless you also delete the
  1196. * imported module from :py:data:`sys.modules`. This calls
  1197. * :func:`~pyodide.ffi.unregister_js_module`.
  1198. *
  1199. * @param name Name of the JavaScript module to remove
  1200. */
  1201. static unregisterJsModule(name: string): void;
  1202. /**
  1203. * Convert a JavaScript object to a Python object as best as possible.
  1204. *
  1205. * This is similar to :py:meth:`~pyodide.ffi.JsProxy.to_py` but for use from
  1206. * JavaScript. If the object is immutable or a :js:class:`~pyodide.ffi.PyProxy`,
  1207. * it will be returned unchanged. If the object cannot be converted into Python,
  1208. * it will be returned unchanged.
  1209. *
  1210. * See :ref:`type-translations-jsproxy-to-py` for more information.
  1211. *
  1212. * @param obj The object to convert.
  1213. * @param options
  1214. * @returns The object converted to Python.
  1215. */
  1216. static toPy(obj: any, { depth, defaultConverter, }?: {
  1217. /**
  1218. * Optional argument to limit the depth of the conversion.
  1219. */
  1220. depth: number;
  1221. /**
  1222. * Optional argument to convert objects with no default conversion. See the
  1223. * documentation of :py:meth:`~pyodide.ffi.JsProxy.to_py`.
  1224. */
  1225. defaultConverter?: (value: any, converter: (value: any) => any, cacheConversion: (input: any, output: any) => void) => any;
  1226. }): any;
  1227. /**
  1228. * Imports a module and returns it.
  1229. *
  1230. * If `name` has no dot in it, then `pyimport(name)` is approximately
  1231. * equivalent to:
  1232. * ```js
  1233. * pyodide.runPython(`import ${name}; ${name}`)
  1234. * ```
  1235. * except that `name` is not introduced into the Python global namespace. If
  1236. * the name has one or more dots in it, say it is of the form `path.name`
  1237. * where `name` has no dots but path may have zero or more dots. Then it is
  1238. * approximately the same as:
  1239. * ```js
  1240. * pyodide.runPython(`from ${path} import ${name}; ${name}`);
  1241. * ```
  1242. *
  1243. * @param mod_name The name of the module to import
  1244. *
  1245. * @example
  1246. * pyodide.pyimport("math.comb")(4, 2) // returns 4 choose 2 = 6
  1247. */
  1248. static pyimport(mod_name: string): any;
  1249. /**
  1250. * Unpack an archive into a target directory.
  1251. *
  1252. * @param buffer The archive as an :js:class:`ArrayBuffer` or :js:class:`TypedArray`.
  1253. * @param format The format of the archive. Should be one of the formats
  1254. * recognized by :py:func:`shutil.unpack_archive`. By default the options are
  1255. * ``'bztar'``, ``'gztar'``, ``'tar'``, ``'zip'``, and ``'wheel'``. Several
  1256. * synonyms are accepted for each format, e.g., for ``'gztar'`` any of
  1257. * ``'.gztar'``, ``'.tar.gz'``, ``'.tgz'``, ``'tar.gz'`` or ``'tgz'`` are
  1258. * considered to be
  1259. * synonyms.
  1260. *
  1261. * @param options
  1262. * @param options.extractDir The directory to unpack the archive into. Defaults
  1263. * to the working directory.
  1264. */
  1265. static unpackArchive(buffer: TypedArray | ArrayBuffer, format: string, options?: {
  1266. extractDir?: string;
  1267. }): void;
  1268. /**
  1269. * Mounts a :js:class:`FileSystemDirectoryHandle` into the target directory.
  1270. * Currently it's only possible to acquire a
  1271. * :js:class:`FileSystemDirectoryHandle` in Chrome.
  1272. *
  1273. * @param path The absolute path in the Emscripten file system to mount the
  1274. * native directory. If the directory does not exist, it will be created. If
  1275. * it does exist, it must be empty.
  1276. * @param fileSystemHandle A handle returned by
  1277. * :js:func:`navigator.storage.getDirectory() <getDirectory>` or
  1278. * :js:func:`window.showDirectoryPicker() <showDirectoryPicker>`.
  1279. */
  1280. static mountNativeFS(path: string, fileSystemHandle: FileSystemDirectoryHandle): Promise<NativeFS>;
  1281. /**
  1282. * Mounts a host directory into Pyodide file system. Only works in node.
  1283. *
  1284. * @param emscriptenPath The absolute path in the Emscripten file system to
  1285. * mount the native directory. If the directory does not exist, it will be
  1286. * created. If it does exist, it must be empty.
  1287. * @param hostPath The host path to mount. It must be a directory that exists.
  1288. */
  1289. static mountNodeFS(emscriptenPath: string, hostPath: string): void;
  1290. /**
  1291. * Tell Pyodide about Comlink.
  1292. * Necessary to enable importing Comlink proxies into Python.
  1293. */
  1294. static registerComlink(Comlink: any): void;
  1295. /**
  1296. * Sets the interrupt buffer to be ``interrupt_buffer``. This is only useful
  1297. * when Pyodide is used in a webworker. The buffer should be a
  1298. * :js:class:`SharedArrayBuffer` shared with the main browser thread (or another
  1299. * worker). In that case, signal ``signum`` may be sent by writing ``signum``
  1300. * into the interrupt buffer. If ``signum`` does not satisfy 0 < ``signum`` < 65
  1301. * it will be silently ignored.
  1302. *
  1303. * You can disable interrupts by calling ``setInterruptBuffer(undefined)``.
  1304. *
  1305. * If you wish to trigger a :py:exc:`KeyboardInterrupt`, write ``SIGINT`` (a 2)
  1306. * into the interrupt buffer.
  1307. *
  1308. * By default ``SIGINT`` raises a :py:exc:`KeyboardInterrupt` and all other signals
  1309. * are ignored. You can install custom signal handlers with the signal module.
  1310. * Even signals that normally have special meaning and can't be overridden like
  1311. * ``SIGKILL`` and ``SIGSEGV`` are ignored by default and can be used for any
  1312. * purpose you like.
  1313. */
  1314. static setInterruptBuffer(interrupt_buffer: TypedArray): void;
  1315. /**
  1316. * Throws a :py:exc:`KeyboardInterrupt` error if a :py:exc:`KeyboardInterrupt` has
  1317. * been requested via the interrupt buffer.
  1318. *
  1319. * This can be used to enable keyboard interrupts during execution of JavaScript
  1320. * code, just as :c:func:`PyErr_CheckSignals` is used to enable keyboard interrupts
  1321. * during execution of C code.
  1322. */
  1323. static checkInterrupt(): void;
  1324. /**
  1325. * Turn on or off debug mode. In debug mode, some error messages are improved
  1326. * at a performance cost.
  1327. * @param debug If true, turn debug mode on. If false, turn debug mode off.
  1328. * @returns The old value of the debug flag.
  1329. */
  1330. static setDebug(debug: boolean): boolean;
  1331. }
  1332. /** @hidetype */
  1333. export type PyodideInterface = typeof PyodideAPI;
  1334. /**
  1335. * See documentation for loadPyodide.
  1336. * @private
  1337. */
  1338. type ConfigType = {
  1339. indexURL: string;
  1340. packageCacheDir: string;
  1341. lockFileURL: string;
  1342. fullStdLib?: boolean;
  1343. stdLibURL?: string;
  1344. stdin?: () => string;
  1345. stdout?: (msg: string) => void;
  1346. stderr?: (msg: string) => void;
  1347. jsglobals?: object;
  1348. args: string[];
  1349. _node_mounts: string[];
  1350. env: {
  1351. [key: string]: string;
  1352. };
  1353. packages: string[];
  1354. };
  1355. /**
  1356. * Load the main Pyodide wasm module and initialize it.
  1357. *
  1358. * @returns The :ref:`js-api-pyodide` module.
  1359. * @memberof globalThis
  1360. * @async
  1361. * @example
  1362. * async function main() {
  1363. * const pyodide = await loadPyodide({
  1364. * fullStdLib: true,
  1365. * stdout: (msg) => console.log(`Pyodide: ${msg}`),
  1366. * });
  1367. * console.log("Loaded Pyodide");
  1368. * }
  1369. * main();
  1370. */
  1371. export declare function loadPyodide(options?: {
  1372. /**
  1373. * The URL from which Pyodide will load the main Pyodide runtime and
  1374. * packages. It is recommended that you leave this unchanged, providing an
  1375. * incorrect value can cause broken behavior.
  1376. *
  1377. * Default: The url that Pyodide is loaded from with the file name
  1378. * (``pyodide.js`` or ``pyodide.mjs``) removed.
  1379. */
  1380. indexURL?: string;
  1381. /**
  1382. * The file path where packages will be cached in node. If a package
  1383. * exists in ``packageCacheDir`` it is loaded from there, otherwise it is
  1384. * downloaded from the JsDelivr CDN and then cached into ``packageCacheDir``.
  1385. * Only applies when running in node; ignored in browsers.
  1386. *
  1387. * Default: same as indexURL
  1388. */
  1389. packageCacheDir?: string;
  1390. /**
  1391. * The URL from which Pyodide will load the Pyodide ``pyodide-lock.json`` lock
  1392. * file. You can produce custom lock files with :py:func:`micropip.freeze`.
  1393. * Default: ```${indexURL}/pyodide-lock.json```
  1394. */
  1395. lockFileURL?: string;
  1396. /**
  1397. * Load the full Python standard library. Setting this to false excludes
  1398. * unvendored modules from the standard library.
  1399. * Default: ``false``
  1400. */
  1401. fullStdLib?: boolean;
  1402. /**
  1403. * The URL from which to load the standard library ``python_stdlib.zip``
  1404. * file. This URL includes the most of the Python standard library. Some
  1405. * stdlib modules were unvendored, and can be loaded separately
  1406. * with ``fullStdLib: true`` option or by their package name.
  1407. * Default: ```${indexURL}/python_stdlib.zip```
  1408. */
  1409. stdLibURL?: string;
  1410. /**
  1411. * Override the standard input callback. Should ask the user for one line of
  1412. * input. The :js:func:`pyodide.setStdin` function is more flexible and
  1413. * should be preferred.
  1414. */
  1415. stdin?: () => string;
  1416. /**
  1417. * Override the standard output callback. The :js:func:`pyodide.setStdout`
  1418. * function is more flexible and should be preferred in most cases, but
  1419. * depending on the ``args`` passed to ``loadPyodide``, Pyodide may write to
  1420. * stdout on startup, which can only be controlled by passing a custom
  1421. * ``stdout`` function.
  1422. */
  1423. stdout?: (msg: string) => void;
  1424. /**
  1425. * Override the standard error output callback. The
  1426. * :js:func:`pyodide.setStderr` function is more flexible and should be
  1427. * preferred in most cases, but depending on the ``args`` passed to
  1428. * ``loadPyodide``, Pyodide may write to stdout on startup, which can only
  1429. * be controlled by passing a custom ``stdout`` function.
  1430. */
  1431. stderr?: (msg: string) => void;
  1432. /**
  1433. * The object that Pyodide will use for the ``js`` module.
  1434. * Default: ``globalThis``
  1435. */
  1436. jsglobals?: object;
  1437. /**
  1438. * Command line arguments to pass to Python on startup. See `Python command
  1439. * line interface options
  1440. * <https://docs.python.org/3.10/using/cmdline.html#interface-options>`_ for
  1441. * more details. Default: ``[]``
  1442. */
  1443. args?: string[];
  1444. /**
  1445. * Environment variables to pass to Python. This can be accessed inside of
  1446. * Python at runtime via :py:data:`os.environ`. Certain environment variables change
  1447. * the way that Python loads:
  1448. * https://docs.python.org/3.10/using/cmdline.html#environment-variables
  1449. * Default: ``{}``.
  1450. * If ``env.HOME`` is undefined, it will be set to a default value of
  1451. * ``"/home/pyodide"``
  1452. */
  1453. env?: {
  1454. [key: string]: string;
  1455. };
  1456. /**
  1457. * A list of packages to load as Pyodide is initializing.
  1458. *
  1459. * This is the same as loading the packages with
  1460. * :js:func:`pyodide.loadPackage` after Pyodide is loaded except using the
  1461. * ``packages`` option is more efficient because the packages are downloaded
  1462. * while Pyodide bootstraps itself.
  1463. */
  1464. packages?: string[];
  1465. /**
  1466. * Opt into the old behavior where PyProxy.toString calls `repr` and not
  1467. * `str`.
  1468. * @deprecated
  1469. */
  1470. pyproxyToStringRepr?: boolean;
  1471. /**
  1472. * @ignore
  1473. */
  1474. _node_mounts?: string[];
  1475. }): Promise<PyodideInterface>;
  1476. export type {};
  1477. export type {};