Last active
February 2, 2024 10:16
-
-
Save ykrods/a9aa6cbb400a32a43c231d6d70f70a0a to your computer and use it in GitHub Desktop.
pyodide メモ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* js -> python でデータを渡す方法 | |
* | |
* ユーザ入力をそのまま runPython(`${x}`) とかすると危なそうなので、変数として渡したい場合 | |
* | |
* 参考: https://pyodide.org/en/stable/usage/type-conversions.html#calling-python-objects-from-javascript | |
*/ | |
const pyodide = await loadPyodide(); | |
pyodide.global.set("x", 1); | |
pyodide.runPython("x * 2"); | |
// グローバル変数を使いたくない場合 | |
// 1. Pythonの関数をjsから呼ぶ | |
const twice = pyodide.runPython(` | |
from pyodide.ffi import to_js | |
def t(x): return to_js(x * 2) | |
t | |
`); | |
console.log(twice(1)); // => 2 | |
// 2. globals オブジェクトを runPythonなどに渡す | |
// globals は PyProxy 型である必要がある | |
let globals = pyodide.toPy({x: 1}); | |
pyodide.runPython("x * 2", { options: globals }); | |
globals.destroy(); | |
// これだと普通にグローバル変数に入ってしまう(期待してる動作?) | |
const globals = pyodide.globals.copy(); | |
globals.set("x", 1); | |
globals.destroy(); | |
pyodide.globals.get("x"); // => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
バージョンアップで名前空間を分けられるようになった。(0.25.0 のいくらか前からからできていた感があるが)
https://pyodide.org/en/stable/usage/faq.html#how-can-i-execute-code-in-a-custom-namespace