Skip to content

Commit

Permalink
Python: Add vendor directory to the path automatically if present
Browse files Browse the repository at this point in the history
This won't work yet with top level imports from the vendor directory
because of snapshot problems. I am leaving that to a followup.
  • Loading branch information
hoodmane committed Feb 26, 2025
1 parent ded1c30 commit 8b62a8d
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 4 deletions.
12 changes: 12 additions & 0 deletions src/pyodide/internal/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,18 @@ export async function loadPyodide(
(msg) => console.log(msg),
(msg) => console.error(msg)
);
pyodide.runPython(`
def _tmp():
import sys
from pathlib import Path
VENDOR_PATH = "/session/metadata/vendor"
print(VENDOR_PATH, Path(VENDOR_PATH).is_dir())
if Path(VENDOR_PATH).is_dir():
sys.path.append(VENDOR_PATH)
_tmp()
del _tmp
`);
return pyodide;
}
1 change: 1 addition & 0 deletions src/pyodide/types/Pyodide.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ interface PyModule {

interface Pyodide {
_module: Module;
runPython: (code: string) => void;
registerJsModule: (handle: string, mod: object) => void;
pyimport: (moduleName: string) => PyModule;
FS: FS;
Expand Down
11 changes: 7 additions & 4 deletions src/workerd/server/tests/python/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,13 @@ py_wd_test("seek-metadatafs")
py_wd_test(
"undefined-handler",
# TODO: Requires a new bundle deploy
skip_python_flags = [
"0.26.0a2",
"0.27.1",
],
python_flags = ["development"],
)

py_wd_test(
"vendor_dir",
# TODO: Requires a new bundle deploy
python_flags = ["development"],
)

py_wd_test("dont-snapshot-pyodide")
Expand Down
1 change: 1 addition & 0 deletions src/workerd/server/tests/python/vendor_dir/vendor/a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A = 77
16 changes: 16 additions & 0 deletions src/workerd/server/tests/python/vendor_dir/vendor_dir.wd-test
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Workerd = import "/workerd/workerd.capnp";

const unitTests :Workerd.Config = (
services = [
( name = "vendor_dir",
worker = (
modules = [
(name = "worker.py", pythonModule = embed "worker.py"),
(name = "vendor/a.py", pythonModule = embed "vendor/a.py")
],
compatibilityDate = "2024-01-15",
compatibilityFlags = [%PYTHON_FEATURE_FLAGS],
)
),
],
);
4 changes: 4 additions & 0 deletions src/workerd/server/tests/python/vendor_dir/worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def test():
from a import A

assert A == 77

0 comments on commit 8b62a8d

Please sign in to comment.