pyodide.d.ts 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  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 key word arguments. The last argument must be an
  656. * object with the keyword arguments.
  657. */
  658. callKwargs(...jsargs: any): any;
  659. /**
  660. * Call the function with stack switching enabled. Functions called this way
  661. * can use
  662. * :py:meth:`PyodideFuture.syncify() <pyodide.webloop.PyodideFuture.syncify>`
  663. * to block until a :py:class:`~asyncio.Future` or :js:class:`Promise` is
  664. * resolved. Only works in runtimes with JS Promise integration.
  665. *
  666. * .. admonition:: Experimental
  667. * :class: warning
  668. *
  669. * This feature is not yet stable.
  670. *
  671. * @experimental
  672. */
  673. callSyncifying(...jsargs: any): Promise<any>;
  674. /**
  675. * Call the function with stack switching enabled. The last argument must be
  676. * an object with the keyword arguments. Functions called this way can use
  677. * :py:meth:`PyodideFuture.syncify() <pyodide.webloop.PyodideFuture.syncify>`
  678. * to block until a :py:class:`~asyncio.Future` or :js:class:`Promise` is
  679. * resolved. Only works in runtimes with JS Promise integration.
  680. *
  681. * .. admonition:: Experimental
  682. * :class: warning
  683. *
  684. * This feature is not yet stable.
  685. *
  686. * @experimental
  687. */
  688. callSyncifyingKwargs(...jsargs: any): Promise<any>;
  689. /**
  690. * The ``bind()`` method creates a new function that, when called, has its
  691. * ``this`` keyword set to the provided value, with a given sequence of
  692. * arguments preceding any provided when the new function is called. See
  693. * :js:meth:`Function.bind`.
  694. *
  695. * If the :js:class:`~pyodide.ffi.PyCallable` does not have
  696. * :js:meth:`captureThis` set, the ``this`` parameter will be discarded. If it
  697. * does have :js:meth:`captureThis` set, ``thisArg`` will be set to the first
  698. * argument of the Python function. The returned proxy and the original proxy
  699. * have the same lifetime so destroying either destroys both.
  700. *
  701. * @param thisArg The value to be passed as the ``this`` parameter to the
  702. * target function ``func`` when the bound function is called.
  703. * @param jsargs Extra arguments to prepend to arguments provided to the bound
  704. * function when invoking ``func``.
  705. * @returns
  706. */
  707. bind(thisArg: any, ...jsargs: any): PyProxy;
  708. /**
  709. * Returns a :js:class:`~pyodide.ffi.PyProxy` that passes ``this`` as the first argument to the
  710. * Python function. The returned :js:class:`~pyodide.ffi.PyProxy` has the internal ``captureThis``
  711. * property set.
  712. *
  713. * It can then be used as a method on a JavaScript object. The returned proxy
  714. * and the original proxy have the same lifetime so destroying either destroys
  715. * both.
  716. *
  717. * For example:
  718. *
  719. * .. code-block:: pyodide
  720. *
  721. * let obj = { a : 7 };
  722. * pyodide.runPython(`
  723. * def f(self):
  724. * return self.a
  725. * `);
  726. * // Without captureThis, it doesn't work to use f as a method for obj:
  727. * obj.f = pyodide.globals.get("f");
  728. * obj.f(); // raises "TypeError: f() missing 1 required positional argument: 'self'"
  729. * // With captureThis, it works fine:
  730. * obj.f = pyodide.globals.get("f").captureThis();
  731. * obj.f(); // returns 7
  732. *
  733. * @returns The resulting :js:class:`~pyodide.ffi.PyProxy`. It has the same lifetime as the
  734. * original :js:class:`~pyodide.ffi.PyProxy` but passes ``this`` to the wrapped function.
  735. *
  736. */
  737. captureThis(): PyProxy;
  738. }
  739. declare class PyBuffer extends PyProxy {
  740. /** @private */
  741. static [Symbol.hasInstance](obj: any): obj is PyBuffer;
  742. }
  743. /** @deprecated Use `import type { PyBuffer } from "pyodide/ffi"` instead */
  744. interface PyBuffer extends PyBufferMethods {
  745. }
  746. declare class PyBufferMethods {
  747. /**
  748. * Get a view of the buffer data which is usable from JavaScript. No copy is
  749. * ever performed.
  750. *
  751. * We do not support suboffsets, if the buffer requires suboffsets we will
  752. * throw an error. JavaScript nd array libraries can't handle suboffsets
  753. * anyways. In this case, you should use the :js:meth:`~PyProxy.toJs` api or
  754. * copy the buffer to one that doesn't use suboffsets (using e.g.,
  755. * :py:func:`numpy.ascontiguousarray`).
  756. *
  757. * If the buffer stores big endian data or half floats, this function will
  758. * fail without an explicit type argument. For big endian data you can use
  759. * :js:meth:`~PyProxy.toJs`. :js:class:`DataView` has support for big endian
  760. * data, so you might want to pass ``'dataview'`` as the type argument in that
  761. * case.
  762. *
  763. * @param type The type of the :js:attr:`~pyodide.ffi.PyBufferView.data` field
  764. * in the output. Should be one of: ``"i8"``, ``"u8"``, ``"u8clamped"``,
  765. * ``"i16"``, ``"u16"``, ``"i32"``, ``"u32"``, ``"i32"``, ``"u32"``,
  766. * ``"i64"``, ``"u64"``, ``"f32"``, ``"f64``, or ``"dataview"``. This argument
  767. * is optional, if absent :js:meth:`~pyodide.ffi.PyBuffer.getBuffer` will try
  768. * to determine the appropriate output type based on the buffer format string
  769. * (see :std:ref:`struct-format-strings`).
  770. */
  771. getBuffer(type?: string): PyBufferView;
  772. }
  773. declare class PyDict extends PyProxy {
  774. /** @private */
  775. static [Symbol.hasInstance](obj: any): obj is PyProxy;
  776. }
  777. /** @deprecated Use `import type { PyDict } from "pyodide/ffi"` instead */
  778. interface PyDict extends PyProxyWithGet, PyProxyWithSet, PyProxyWithHas, PyProxyWithLength, PyIterable {
  779. }
  780. /** @deprecated Use `import type { PyBufferView } from "pyodide/ffi"` instead */
  781. declare class PyBufferView {
  782. /**
  783. * The offset of the first entry of the array. For instance if our array
  784. * is 3d, then you will find ``array[0,0,0]`` at
  785. * ``pybuf.data[pybuf.offset]``
  786. */
  787. offset: number;
  788. /**
  789. * If the data is read only, you should not modify it. There is no way for us
  790. * to enforce this, but it may cause very weird behavior. See
  791. * :py:attr:`memoryview.readonly`.
  792. */
  793. readonly: boolean;
  794. /**
  795. * The format string for the buffer. See :ref:`struct-format-strings`
  796. * and :py:attr:`memoryview.format`.
  797. */
  798. format: string;
  799. /**
  800. * How large is each entry in bytes? See :py:attr:`memoryview.itemsize`.
  801. */
  802. itemsize: number;
  803. /**
  804. * The number of dimensions of the buffer. If ``ndim`` is 0, the buffer
  805. * represents a single scalar or struct. Otherwise, it represents an
  806. * array. See :py:attr:`memoryview.ndim`.
  807. */
  808. ndim: number;
  809. /**
  810. * The total number of bytes the buffer takes up. This is equal to
  811. * :js:attr:`buff.data.byteLength <TypedArray.byteLength>`. See :py:attr:`memoryview.nbytes`.
  812. */
  813. nbytes: number;
  814. /**
  815. * The shape of the buffer, that is how long it is in each dimension.
  816. * The length will be equal to ``ndim``. For instance, a 2x3x4 array
  817. * would have shape ``[2, 3, 4]``. See :py:attr:`memoryview.shape`.
  818. */
  819. shape: number[];
  820. /**
  821. * An array of of length ``ndim`` giving the number of elements to skip
  822. * to get to a new element in each dimension. See the example definition
  823. * of a ``multiIndexToIndex`` function above. See :py:attr:`memoryview.strides`.
  824. */
  825. strides: number[];
  826. /**
  827. * The actual data. A typed array of an appropriate size backed by a segment
  828. * of the WASM memory.
  829. *
  830. * The ``type`` argument of :js:meth:`~pyodide.ffi.PyBuffer.getBuffer` determines
  831. * which sort of :js:class:`TypedArray` or :js:class:`DataView` to return. By
  832. * default :js:meth:`~pyodide.ffi.PyBuffer.getBuffer` will look at the format string
  833. * to determine the most appropriate option. Most often the result is a
  834. * :js:class:`Uint8Array`.
  835. *
  836. * .. admonition:: Contiguity
  837. * :class: warning
  838. *
  839. * If the buffer is not contiguous, the :js:attr:`~PyBufferView.readonly`
  840. * TypedArray will contain data that is not part of the buffer. Modifying
  841. * this data leads to undefined behavior.
  842. *
  843. * .. admonition:: Read only buffers
  844. * :class: warning
  845. *
  846. * If :js:attr:`buffer.readonly <PyBufferView.readonly>` is ``true``, you
  847. * should not modify the buffer. Modifying a read only buffer leads to
  848. * undefined behavior.
  849. *
  850. */
  851. data: TypedArray;
  852. /**
  853. * Is it C contiguous? See :py:attr:`memoryview.c_contiguous`.
  854. */
  855. c_contiguous: boolean;
  856. /**
  857. * Is it Fortran contiguous? See :py:attr:`memoryview.f_contiguous`.
  858. */
  859. f_contiguous: boolean;
  860. _released: boolean;
  861. _view_ptr: number;
  862. /** @private */
  863. constructor();
  864. /**
  865. * Release the buffer. This allows the memory to be reclaimed.
  866. */
  867. release(): void;
  868. }
  869. type InFuncType = () => null | undefined | string | ArrayBuffer | Uint8Array | number;
  870. declare function setStdin(options?: {
  871. stdin?: InFuncType;
  872. read?: (buffer: Uint8Array) => number;
  873. error?: boolean;
  874. isatty?: boolean;
  875. autoEOF?: boolean;
  876. }): void;
  877. declare function setStdout(options?: {
  878. batched?: (output: string) => void;
  879. raw?: (charCode: number) => void;
  880. write?: (buffer: Uint8Array) => number;
  881. isatty?: boolean;
  882. }): void;
  883. declare function setStderr(options?: {
  884. batched?: (output: string) => void;
  885. raw?: (charCode: number) => void;
  886. write?: (buffer: Uint8Array) => number;
  887. isatty?: boolean;
  888. }): void;
  889. type PackageType = "package" | "cpython_module" | "shared_library" | "static_library";
  890. export type PackageData = {
  891. name: string;
  892. version: string;
  893. fileName: string;
  894. /** @experimental */
  895. packageType: PackageType;
  896. };
  897. declare function loadPackage(names: string | PyProxy | Array<string>, options?: {
  898. messageCallback?: (message: string) => void;
  899. errorCallback?: (message: string) => void;
  900. checkIntegrity?: boolean;
  901. }): Promise<Array<PackageData>>;
  902. /** @deprecated Use `import type { TypedArray } from "pyodide/ffi"` instead */
  903. export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array;
  904. interface CanvasInterface {
  905. setCanvas2D(canvas: HTMLCanvasElement): void;
  906. getCanvas2D(): HTMLCanvasElement | undefined;
  907. setCanvas3D(canvas: HTMLCanvasElement): void;
  908. getCanvas3D(): HTMLCanvasElement | undefined;
  909. }
  910. declare class PythonError extends Error {
  911. /**
  912. * The address of the error we are wrapping. We may later compare this
  913. * against sys.last_value.
  914. * WARNING: we don't own a reference to this pointer, dereferencing it
  915. * may be a use-after-free error!
  916. * @private
  917. */
  918. __error_address: number;
  919. /**
  920. * The name of the Python error class, e.g, :py:exc:`RuntimeError` or
  921. * :py:exc:`KeyError`.
  922. */
  923. type: string;
  924. constructor(type: string, message: string, error_address: number);
  925. }
  926. type NativeFS = {
  927. syncfs: () => Promise<void>;
  928. };
  929. declare class PyodideAPI {
  930. /** @hidden */
  931. static version: string;
  932. /** @hidden */
  933. static loadPackage: typeof loadPackage;
  934. /** @hidden */
  935. static loadedPackages: {
  936. [key: string]: string;
  937. };
  938. /** @hidden */
  939. static ffi: {
  940. PyProxy: typeof PyProxy;
  941. PyProxyWithLength: typeof PyProxyWithLength;
  942. PyProxyWithGet: typeof PyProxyWithGet;
  943. PyProxyWithSet: typeof PyProxyWithSet;
  944. PyProxyWithHas: typeof PyProxyWithHas;
  945. PyDict: typeof PyDict;
  946. PyIterable: typeof PyIterable;
  947. PyAsyncIterable: typeof PyAsyncIterable;
  948. PyIterator: typeof PyIterator;
  949. PyAsyncIterator: typeof PyAsyncIterator;
  950. PyGenerator: typeof PyGenerator;
  951. PyAsyncGenerator: typeof PyAsyncGenerator;
  952. PyAwaitable: typeof PyAwaitable;
  953. PyCallable: typeof PyCallable;
  954. PyBuffer: typeof PyBuffer;
  955. PyBufferView: typeof PyBufferView;
  956. PythonError: typeof PythonError;
  957. PySequence: typeof PySequence;
  958. PyMutableSequence: typeof PyMutableSequence;
  959. };
  960. /** @hidden */
  961. static setStdin: typeof setStdin;
  962. /** @hidden */
  963. static setStdout: typeof setStdout;
  964. /** @hidden */
  965. static setStderr: typeof setStderr;
  966. /**
  967. *
  968. * An alias to the global Python namespace.
  969. *
  970. * For example, to access a variable called ``foo`` in the Python global
  971. * scope, use ``pyodide.globals.get("foo")``
  972. */
  973. static globals: PyProxy;
  974. /**
  975. * An alias to the `Emscripten File System API
  976. * <https://emscripten.org/docs/api_reference/Filesystem-API.html>`_.
  977. *
  978. * This provides a wide range of POSIX-`like` file/device operations, including
  979. * `mount
  980. * <https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.mount>`_
  981. * which can be used to extend the in-memory filesystem with features like `persistence
  982. * <https://emscripten.org/docs/api_reference/Filesystem-API.html#persistent-data>`_.
  983. *
  984. * While all the file systems implementations are enabled, only the default
  985. * ``MEMFS`` is guaranteed to work in all runtime settings. The implementations
  986. * are available as members of ``FS.filesystems``:
  987. * ``IDBFS``, ``NODEFS``, ``PROXYFS``, ``WORKERFS``.
  988. */
  989. static FS: any;
  990. /**
  991. * An alias to the `Emscripten Path API
  992. * <https://github.com/emscripten-core/emscripten/blob/main/src/library_path.js>`_.
  993. *
  994. * This provides a variety of operations for working with file system paths, such as
  995. * ``dirname``, ``normalize``, and ``splitPath``.
  996. */
  997. static PATH: any;
  998. /**
  999. * See :ref:`js-api-pyodide-canvas`.
  1000. * @hidetype
  1001. */
  1002. static canvas: CanvasInterface;
  1003. /**
  1004. * A map from posix error names to error codes.
  1005. */
  1006. static ERRNO_CODES: {
  1007. [code: string]: number;
  1008. };
  1009. /**
  1010. * An alias to the Python :ref:`pyodide <python-api>` package.
  1011. *
  1012. * You can use this to call functions defined in the Pyodide Python package
  1013. * from JavaScript.
  1014. */
  1015. static pyodide_py: PyProxy;
  1016. /**
  1017. * Inspect a Python code chunk and use :js:func:`pyodide.loadPackage` to install
  1018. * any known packages that the code chunk imports. Uses the Python API
  1019. * :func:`pyodide.code.find\_imports` to inspect the code.
  1020. *
  1021. * For example, given the following code as input
  1022. *
  1023. * .. code-block:: python
  1024. *
  1025. * import numpy as np
  1026. * x = np.array([1, 2, 3])
  1027. *
  1028. * :js:func:`loadPackagesFromImports` will call
  1029. * ``pyodide.loadPackage(['numpy'])``.
  1030. *
  1031. * @param code The code to inspect.
  1032. * @param options Options passed to :js:func:`pyodide.loadPackage`.
  1033. * @param options.messageCallback A callback, called with progress messages
  1034. * (optional)
  1035. * @param options.errorCallback A callback, called with error/warning messages
  1036. * (optional)
  1037. * @param options.checkIntegrity If true, check the integrity of the downloaded
  1038. * packages (default: true)
  1039. * @async
  1040. */
  1041. static loadPackagesFromImports(code: string, options?: {
  1042. messageCallback?: (message: string) => void;
  1043. errorCallback?: (message: string) => void;
  1044. checkIntegrity?: boolean;
  1045. }): Promise<Array<PackageData>>;
  1046. /**
  1047. * Runs a string of Python code from JavaScript, using :py:func:`~pyodide.code.eval_code`
  1048. * to evaluate the code. If the last statement in the Python code is an
  1049. * expression (and the code doesn't end with a semicolon), the value of the
  1050. * expression is returned.
  1051. *
  1052. * @param code The Python code to run
  1053. * @param options
  1054. * @param options.globals An optional Python dictionary to use as the globals.
  1055. * Defaults to :js:attr:`pyodide.globals`.
  1056. * @param options.locals An optional Python dictionary to use as the locals.
  1057. * Defaults to the same as ``globals``.
  1058. * @param options.filename An optional string to use as the file name.
  1059. * Defaults to ``"<exec>"``. If a custom file name is given, the
  1060. * traceback for any exception that is thrown will show source lines
  1061. * (unless the given file name starts with ``<`` and ends with ``>``).
  1062. * @returns The result of the Python code translated to JavaScript. See the
  1063. * documentation for :py:func:`~pyodide.code.eval_code` for more info.
  1064. * @example
  1065. * async function main(){
  1066. * const pyodide = await loadPyodide();
  1067. * console.log(pyodide.runPython("1 + 2"));
  1068. * // 3
  1069. *
  1070. * const globals = pyodide.toPy({ x: 3 });
  1071. * console.log(pyodide.runPython("x + 1", { globals }));
  1072. * // 4
  1073. *
  1074. * const locals = pyodide.toPy({ arr: [1, 2, 3] });
  1075. * console.log(pyodide.runPython("sum(arr)", { locals }));
  1076. * // 6
  1077. * }
  1078. * main();
  1079. */
  1080. static runPython(code: string, options?: {
  1081. globals?: PyProxy;
  1082. locals?: PyProxy;
  1083. filename?: string;
  1084. }): any;
  1085. /**
  1086. * Run a Python code string with top level await using
  1087. * :py:func:`~pyodide.code.eval_code_async` to evaluate the code. Returns a promise which
  1088. * resolves when execution completes. If the last statement in the Python code
  1089. * is an expression (and the code doesn't end with a semicolon), the returned
  1090. * promise will resolve to the value of this expression.
  1091. *
  1092. * For example:
  1093. *
  1094. * .. code-block:: pyodide
  1095. *
  1096. * let result = await pyodide.runPythonAsync(`
  1097. * from js import fetch
  1098. * response = await fetch("./pyodide-lock.json")
  1099. * packages = await response.json()
  1100. * # If final statement is an expression, its value is returned to JavaScript
  1101. * len(packages.packages.object_keys())
  1102. * `);
  1103. * console.log(result); // 79
  1104. *
  1105. * .. admonition:: Python imports
  1106. * :class: warning
  1107. *
  1108. * Since pyodide 0.18.0, you must call :js:func:`loadPackagesFromImports` to
  1109. * import any python packages referenced via ``import`` statements in your
  1110. * code. This function will no longer do it for you.
  1111. *
  1112. * @param code The Python code to run
  1113. * @param options
  1114. * @param options.globals An optional Python dictionary to use as the globals.
  1115. * Defaults to :js:attr:`pyodide.globals`.
  1116. * @param options.locals An optional Python dictionary to use as the locals.
  1117. * Defaults to the same as ``globals``.
  1118. * @param options.filename An optional string to use as the file name.
  1119. * Defaults to ``"<exec>"``. If a custom file name is given, the
  1120. * traceback for any exception that is thrown will show source lines
  1121. * (unless the given file name starts with ``<`` and ends with ``>``).
  1122. * @returns The result of the Python code translated to JavaScript.
  1123. * @async
  1124. */
  1125. static runPythonAsync(code: string, options?: {
  1126. globals?: PyProxy;
  1127. locals?: PyProxy;
  1128. filename?: string;
  1129. }): Promise<any>;
  1130. /**
  1131. * Runs a Python code string like :js:func:`pyodide.runPython` but with stack
  1132. * switching enabled. Code executed in this way can use
  1133. * :py:meth:`PyodideFuture.syncify() <pyodide.webloop.PyodideFuture.syncify>`
  1134. * to block until a :py:class:`~asyncio.Future` or :js:class:`Promise` is
  1135. * resolved. Only works in runtimes with JS Promise Integration enabled.
  1136. *
  1137. * .. admonition:: Experimental
  1138. * :class: warning
  1139. *
  1140. * This feature is not yet stable.
  1141. *
  1142. * @experimental
  1143. * @param code The Python code to run
  1144. * @param options
  1145. * @param options.globals An optional Python dictionary to use as the globals.
  1146. * Defaults to :js:attr:`pyodide.globals`.
  1147. * @param options.locals An optional Python dictionary to use as the locals.
  1148. * Defaults to the same as ``globals``.
  1149. * @param options.filename An optional string to use as the file name.
  1150. * Defaults to ``"<exec>"``. If a custom file name is given, the
  1151. * traceback for any exception that is thrown will show source lines
  1152. * (unless the given file name starts with ``<`` and ends with ``>``).
  1153. * @returns The result of the Python code translated to JavaScript.
  1154. */
  1155. static runPythonSyncifying(code: string, options?: {
  1156. globals?: PyProxy;
  1157. locals?: PyProxy;
  1158. filename?: string;
  1159. }): Promise<any>;
  1160. /**
  1161. * Registers the JavaScript object ``module`` as a JavaScript module named
  1162. * ``name``. This module can then be imported from Python using the standard
  1163. * Python import system. If another module by the same name has already been
  1164. * imported, this won't have much effect unless you also delete the imported
  1165. * module from :py:data:`sys.modules`. This calls
  1166. * :func:`~pyodide.ffi.register_js_module`.
  1167. *
  1168. * Any attributes of the JavaScript objects which are themselves objects will
  1169. * be treated as submodules:
  1170. * ```pyodide
  1171. * pyodide.registerJsModule("mymodule", { submodule: { value: 7 } });
  1172. * pyodide.runPython(`
  1173. * from mymodule.submodule import value
  1174. * assert value == 7
  1175. * `);
  1176. * ```
  1177. * If you wish to prevent this, try the following instead:
  1178. * ```pyodide
  1179. * const sys = pyodide.pyimport("sys");
  1180. * sys.modules.set("mymodule", { obj: { value: 7 } });
  1181. * pyodide.runPython(`
  1182. * from mymodule import obj
  1183. * assert obj.value == 7
  1184. * # attempting to treat obj as a submodule raises ModuleNotFoundError:
  1185. * # "No module named 'mymodule.obj'; 'mymodule' is not a package"
  1186. * from mymodule.obj import value
  1187. * `);
  1188. * ```
  1189. *
  1190. * @param name Name of the JavaScript module to add
  1191. * @param module JavaScript object backing the module
  1192. */
  1193. static registerJsModule(name: string, module: object): void;
  1194. /**
  1195. * Unregisters a JavaScript module with given name that has been previously
  1196. * registered with :js:func:`pyodide.registerJsModule` or
  1197. * :func:`~pyodide.ffi.register_js_module`. If a JavaScript module with that
  1198. * name does not already exist, will throw an error. Note that if the module has
  1199. * already been imported, this won't have much effect unless you also delete the
  1200. * imported module from :py:data:`sys.modules`. This calls
  1201. * :func:`~pyodide.ffi.unregister_js_module`.
  1202. *
  1203. * @param name Name of the JavaScript module to remove
  1204. */
  1205. static unregisterJsModule(name: string): void;
  1206. /**
  1207. * Convert a JavaScript object to a Python object as best as possible.
  1208. *
  1209. * This is similar to :py:meth:`~pyodide.ffi.JsProxy.to_py` but for use from
  1210. * JavaScript. If the object is immutable or a :js:class:`~pyodide.ffi.PyProxy`,
  1211. * it will be returned unchanged. If the object cannot be converted into Python,
  1212. * it will be returned unchanged.
  1213. *
  1214. * See :ref:`type-translations-jsproxy-to-py` for more information.
  1215. *
  1216. * @param obj The object to convert.
  1217. * @param options
  1218. * @returns The object converted to Python.
  1219. */
  1220. static toPy(obj: any, { depth, defaultConverter, }?: {
  1221. /**
  1222. * Optional argument to limit the depth of the conversion.
  1223. */
  1224. depth: number;
  1225. /**
  1226. * Optional argument to convert objects with no default conversion. See the
  1227. * documentation of :py:meth:`~pyodide.ffi.JsProxy.to_py`.
  1228. */
  1229. defaultConverter?: (value: any, converter: (value: any) => any, cacheConversion: (input: any, output: any) => void) => any;
  1230. }): any;
  1231. /**
  1232. * Imports a module and returns it.
  1233. *
  1234. * .. admonition:: Warning
  1235. * :class: warning
  1236. *
  1237. * This function has a completely different behavior than the old removed pyimport function!
  1238. *
  1239. * ``pyimport`` is roughly equivalent to:
  1240. *
  1241. * .. code-block:: js
  1242. *
  1243. * pyodide.runPython(`import ${pkgname}; ${pkgname}`);
  1244. *
  1245. * except that the global namespace will not change.
  1246. *
  1247. * Example:
  1248. *
  1249. * .. code-block:: js
  1250. *
  1251. * let sysmodule = pyodide.pyimport("sys");
  1252. * let recursionLimit = sysmodule.getrecursionlimit();
  1253. *
  1254. * @param mod_name The name of the module to import
  1255. * @returns A PyProxy for the imported module
  1256. */
  1257. static pyimport(mod_name: string): PyProxy;
  1258. /**
  1259. * Unpack an archive into a target directory.
  1260. *
  1261. * @param buffer The archive as an :js:class:`ArrayBuffer` or :js:class:`TypedArray`.
  1262. * @param format The format of the archive. Should be one of the formats
  1263. * recognized by :py:func:`shutil.unpack_archive`. By default the options are
  1264. * ``'bztar'``, ``'gztar'``, ``'tar'``, ``'zip'``, and ``'wheel'``. Several
  1265. * synonyms are accepted for each format, e.g., for ``'gztar'`` any of
  1266. * ``'.gztar'``, ``'.tar.gz'``, ``'.tgz'``, ``'tar.gz'`` or ``'tgz'`` are
  1267. * considered to be
  1268. * synonyms.
  1269. *
  1270. * @param options
  1271. * @param options.extractDir The directory to unpack the archive into. Defaults
  1272. * to the working directory.
  1273. */
  1274. static unpackArchive(buffer: TypedArray | ArrayBuffer, format: string, options?: {
  1275. extractDir?: string;
  1276. }): void;
  1277. /**
  1278. * Mounts a :js:class:`FileSystemDirectoryHandle` into the target directory.
  1279. *
  1280. * @param path The absolute path in the Emscripten file system to mount the
  1281. * native directory. If the directory does not exist, it will be created. If it
  1282. * does exist, it must be empty.
  1283. * @param fileSystemHandle A handle returned by :js:func:`navigator.storage.getDirectory() <getDirectory>`
  1284. * or :js:func:`window.showDirectoryPicker() <showDirectoryPicker>`.
  1285. */
  1286. static mountNativeFS(path: string, fileSystemHandle: FileSystemDirectoryHandle): Promise<NativeFS>;
  1287. /**
  1288. * Tell Pyodide about Comlink.
  1289. * Necessary to enable importing Comlink proxies into Python.
  1290. */
  1291. static registerComlink(Comlink: any): void;
  1292. /**
  1293. * Sets the interrupt buffer to be ``interrupt_buffer``. This is only useful
  1294. * when Pyodide is used in a webworker. The buffer should be a
  1295. * :js:class:`SharedArrayBuffer` shared with the main browser thread (or another
  1296. * worker). In that case, signal ``signum`` may be sent by writing ``signum``
  1297. * into the interrupt buffer. If ``signum`` does not satisfy 0 < ``signum`` < 65
  1298. * it will be silently ignored.
  1299. *
  1300. * You can disable interrupts by calling ``setInterruptBuffer(undefined)``.
  1301. *
  1302. * If you wish to trigger a :py:exc:`KeyboardInterrupt`, write ``SIGINT`` (a 2)
  1303. * into the interrupt buffer.
  1304. *
  1305. * By default ``SIGINT`` raises a :py:exc:`KeyboardInterrupt` and all other signals
  1306. * are ignored. You can install custom signal handlers with the signal module.
  1307. * Even signals that normally have special meaning and can't be overridden like
  1308. * ``SIGKILL`` and ``SIGSEGV`` are ignored by default and can be used for any
  1309. * purpose you like.
  1310. */
  1311. static setInterruptBuffer(interrupt_buffer: TypedArray): void;
  1312. /**
  1313. * Throws a :py:exc:`KeyboardInterrupt` error if a :py:exc:`KeyboardInterrupt` has
  1314. * been requested via the interrupt buffer.
  1315. *
  1316. * This can be used to enable keyboard interrupts during execution of JavaScript
  1317. * code, just as :c:func:`PyErr_CheckSignals` is used to enable keyboard interrupts
  1318. * during execution of C code.
  1319. */
  1320. static checkInterrupt(): void;
  1321. /**
  1322. * Turn on or off debug mode. In debug mode, some error messages are improved
  1323. * at a performance cost.
  1324. * @param debug If true, turn debug mode on. If false, turn debug mode off.
  1325. * @returns The old value of the debug flag.
  1326. */
  1327. static setDebug(debug: boolean): boolean;
  1328. }
  1329. /** @hidetype */
  1330. export type PyodideInterface = typeof PyodideAPI;
  1331. /**
  1332. * See documentation for loadPyodide.
  1333. * @private
  1334. */
  1335. type ConfigType = {
  1336. indexURL: string;
  1337. packageCacheDir: string;
  1338. lockFileURL: string;
  1339. fullStdLib?: boolean;
  1340. stdLibURL?: string;
  1341. stdin?: () => string;
  1342. stdout?: (msg: string) => void;
  1343. stderr?: (msg: string) => void;
  1344. jsglobals?: object;
  1345. args: string[];
  1346. _node_mounts: string[];
  1347. env: {
  1348. [key: string]: string;
  1349. };
  1350. packages: string[];
  1351. };
  1352. /**
  1353. * Load the main Pyodide wasm module and initialize it.
  1354. *
  1355. * @returns The :ref:`js-api-pyodide` module.
  1356. * @memberof globalThis
  1357. * @async
  1358. * @example
  1359. * async function main() {
  1360. * const pyodide = await loadPyodide({
  1361. * fullStdLib: true,
  1362. * stdout: (msg) => console.log(`Pyodide: ${msg}`),
  1363. * });
  1364. * console.log("Loaded Pyodide");
  1365. * }
  1366. * main();
  1367. */
  1368. export declare function loadPyodide(options?: {
  1369. /**
  1370. * The URL from which Pyodide will load the main Pyodide runtime and
  1371. * packages. It is recommended that you leave this unchanged, providing an
  1372. * incorrect value can cause broken behavior.
  1373. *
  1374. * Default: The url that Pyodide is loaded from with the file name
  1375. * (``pyodide.js`` or ``pyodide.mjs``) removed.
  1376. */
  1377. indexURL?: string;
  1378. /**
  1379. * The file path where packages will be cached in node. If a package
  1380. * exists in ``packageCacheDir`` it is loaded from there, otherwise it is
  1381. * downloaded from the JsDelivr CDN and then cached into ``packageCacheDir``.
  1382. * Only applies when running in node; ignored in browsers.
  1383. *
  1384. * Default: same as indexURL
  1385. */
  1386. packageCacheDir?: string;
  1387. /**
  1388. * The URL from which Pyodide will load the Pyodide ``pyodide-lock.json`` lock
  1389. * file. You can produce custom lock files with :py:func:`micropip.freeze`.
  1390. * Default: ```${indexURL}/pyodide-lock.json```
  1391. */
  1392. lockFileURL?: string;
  1393. /**
  1394. * Load the full Python standard library. Setting this to false excludes
  1395. * unvendored modules from the standard library.
  1396. * Default: ``false``
  1397. */
  1398. fullStdLib?: boolean;
  1399. /**
  1400. * The URL from which to load the standard library ``python_stdlib.zip``
  1401. * file. This URL includes the most of the Python standard library. Some
  1402. * stdlib modules were unvendored, and can be loaded separately
  1403. * with ``fullStdLib: true`` option or by their package name.
  1404. * Default: ```${indexURL}/python_stdlib.zip```
  1405. */
  1406. stdLibURL?: string;
  1407. /**
  1408. * Override the standard input callback. Should ask the user for one line of
  1409. * input. The :js:func:`pyodide.setStdin` function is more flexible and
  1410. * should be preferred.
  1411. */
  1412. stdin?: () => string;
  1413. /**
  1414. * Override the standard output callback. The :js:func:`pyodide.setStdout`
  1415. * function is more flexible and should be preferred in most cases, but
  1416. * depending on the ``args`` passed to ``loadPyodide``, Pyodide may write to
  1417. * stdout on startup, which can only be controlled by passing a custom
  1418. * ``stdout`` function.
  1419. */
  1420. stdout?: (msg: string) => void;
  1421. /**
  1422. * Override the standard error output callback. The
  1423. * :js:func:`pyodide.setStderr` function is more flexible and should be
  1424. * preferred in most cases, but depending on the ``args`` passed to
  1425. * ``loadPyodide``, Pyodide may write to stdout on startup, which can only
  1426. * be controlled by passing a custom ``stdout`` function.
  1427. */
  1428. stderr?: (msg: string) => void;
  1429. /**
  1430. * The object that Pyodide will use for the ``js`` module.
  1431. * Default: ``globalThis``
  1432. */
  1433. jsglobals?: object;
  1434. /**
  1435. * Command line arguments to pass to Python on startup. See `Python command
  1436. * line interface options
  1437. * <https://docs.python.org/3.10/using/cmdline.html#interface-options>`_ for
  1438. * more details. Default: ``[]``
  1439. */
  1440. args?: string[];
  1441. /**
  1442. * Environment variables to pass to Python. This can be accessed inside of
  1443. * Python at runtime via :py:data:`os.environ`. Certain environment variables change
  1444. * the way that Python loads:
  1445. * https://docs.python.org/3.10/using/cmdline.html#environment-variables
  1446. * Default: ``{}``.
  1447. * If ``env.HOME`` is undefined, it will be set to a default value of
  1448. * ``"/home/pyodide"``
  1449. */
  1450. env?: {
  1451. [key: string]: string;
  1452. };
  1453. /**
  1454. * A list of packages to load as Pyodide is initializing.
  1455. *
  1456. * This is the same as loading the packages with
  1457. * :js:func:`pyodide.loadPackage` after Pyodide is loaded except using the
  1458. * ``packages`` option is more efficient because the packages are downloaded
  1459. * while Pyodide bootstraps itself.
  1460. */
  1461. packages?: string[];
  1462. /**
  1463. * Opt into the old behavior where PyProxy.toString calls `repr` and not
  1464. * `str`.
  1465. * @deprecated
  1466. */
  1467. pyproxyToStringRepr?: boolean;
  1468. /**
  1469. * @ignore
  1470. */
  1471. _node_mounts?: string[];
  1472. }): Promise<PyodideInterface>;
  1473. export type {};
  1474. export type {};