Skip to content

Commit

Permalink
Add instanceMethod
Browse files Browse the repository at this point in the history
  • Loading branch information
sigmaSd committed Jul 16, 2024
1 parent 43e4957 commit 6483b0d
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
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();
});

0 comments on commit 6483b0d

Please sign in to comment.