Skip to content

Commit 58bfb95

Browse files
committed
add support for importing module from python:*
1 parent 5ad6b40 commit 58bfb95

File tree

5 files changed

+39
-14
lines changed

5 files changed

+39
-14
lines changed

examples/import_plugin.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { api_version, version } from "python:sys";
2+
console.log(version);
3+
console.log(api_version);

plugin.ts

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,33 @@ import python from "./index";
55
const { dir } = python.import("builtins");
66
const { SourceFileLoader } = python.import("importlib.machinery");
77

8+
function convertExports(raw: any) {
9+
return Object.fromEntries(
10+
dir(raw)
11+
.valueOf()
12+
.map((key: string) => [key, raw[key]])
13+
)
14+
}
15+
816
plugin({
917
name: "python",
1018
target: "bun",
11-
setup(build) {
12-
// const { default: python } = await import("./index");
13-
build.onLoad({ filter: /\.(py)$/ }, ({ path }) => {
19+
setup({ onResolve, onLoad }) {
20+
onResolve({ filter: /.+/, namespace: "python" }, ({ path }) => {
21+
return { path, namespace: "python" };
22+
});
23+
onLoad({ filter: /.+/, namespace: "python" }, ({ path }) => {
24+
const raw = python.import(path);
25+
const exports = convertExports(raw);
26+
return {
27+
loader: "object",
28+
exports,
29+
};
30+
})
31+
onLoad({ filter: /\.(py)$/ }, ({ path }) => {
1432
const { name } = parse(path);
1533
const raw = SourceFileLoader(name, path).load_module();
16-
const exports = Object.fromEntries(
17-
dir(raw)
18-
.valueOf()
19-
.map((key: string) => [key, raw[key]])
20-
);
34+
const exports = convertExports(raw);
2135
return {
2236
loader: "object",
2337
exports,

python.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
declare module "python:*";
2+
3+
declare module "*.py";

test/plugin.test.js

Lines changed: 0 additions & 6 deletions
This file was deleted.

test/plugin.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { expect, test } from "bun:test";
2+
import { max } from "python:builtins";
3+
import { hello } from "./test.py";
4+
5+
test("load builtins module", () => {
6+
expect(max(1, 2).valueOf()).toBe(2);
7+
});
8+
9+
test("load py as module", () => {
10+
expect(hello("world").valueOf()).toBe("hello world");
11+
});

0 commit comments

Comments
 (0)