Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add instanceMethod #68

Merged
merged 3 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,34 @@ export class Python {
callback(cb: PythonJSCallback): Callback {
return new Callback(cb);
}

/**
* Creates a Python instance method from a JavaScript callback.
*
* @description
* This method takes a JavaScript callback function and creates a Python instance method.
*
* The method returns both the created Python instance method and the Callback object.
* The Callback object is returned to allow the user to explicitly call its `destroy`
* method when it's no longer needed, ensuring proper resource management and
* freeing of memory.
*
* @example
* const [pyMethod, callback] = instanceMethod(myJSFunction);
* // Use pyMethod as needed
* // ...
* // When done, explicitly free the callback
* callback.destroy();
*/
instanceMethod(cb: PythonJSCallback): [PyObject, Callback] {
const pythonCb = python.callback(cb);
const method = new PyObject(
py.PyInstanceMethod_New(
PyObject.from(pythonCb).handle,
),
);
return [method, pythonCb];
}
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/symbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,9 @@ export const SYMBOLS = {
parameters: ["buffer", "pointer", "pointer"],
result: "pointer",
},

PyInstanceMethod_New: {
parameters: ["pointer"],
result: "pointer",
},
} as const;
20 changes: 20 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,23 @@ Deno.test("exceptions", async (t) => {
assertThrows(() => array.shape = [3, 6]);
});
});

Deno.test("instance method", () => {
const { A } = python.runModule(
`
class A:
def b(self):
return 4
`,
"cb_test.py",
);

const [m, cb] = python.instanceMethod((_args, self) => {
return self.b();
});
// Modifying PyObject modifes A
PyObject.from(A).setAttr("a", m);

assertEquals(new A().a.call().valueOf(), 4);
cb.destroy();
});
Loading