File tree Expand file tree Collapse file tree 3 files changed +53
-0
lines changed
Expand file tree Collapse file tree 3 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -975,6 +975,34 @@ export class Python {
975975 callback ( cb : PythonJSCallback ) : Callback {
976976 return new Callback ( cb ) ;
977977 }
978+
979+ /**
980+ * Creates a Python instance method from a JavaScript callback.
981+ *
982+ * @description
983+ * This method takes a JavaScript callback function and creates a Python instance method.
984+ *
985+ * The method returns both the created Python instance method and the Callback object.
986+ * The Callback object is returned to allow the user to explicitly call its `destroy`
987+ * method when it's no longer needed, ensuring proper resource management and
988+ * freeing of memory.
989+ *
990+ * @example
991+ * const [pyMethod, callback] = instanceMethod(myJSFunction);
992+ * // Use pyMethod as needed
993+ * // ...
994+ * // When done, explicitly free the callback
995+ * callback.destroy();
996+ */
997+ instanceMethod ( cb : PythonJSCallback ) : [ PyObject , Callback ] {
998+ const pythonCb = python . callback ( cb ) ;
999+ const method = new PyObject (
1000+ py . PyInstanceMethod_New (
1001+ PyObject . from ( pythonCb ) . handle ,
1002+ ) ,
1003+ ) ;
1004+ return [ method , pythonCb ] ;
1005+ }
9781006}
9791007
9801008/**
Original file line number Diff line number Diff line change @@ -249,4 +249,9 @@ export const SYMBOLS = {
249249 parameters : [ "buffer" , "pointer" , "pointer" ] ,
250250 result : "pointer" ,
251251 } ,
252+
253+ PyInstanceMethod_New : {
254+ parameters : [ "pointer" ] ,
255+ result : "pointer" ,
256+ } ,
252257} as const ;
Original file line number Diff line number Diff line change @@ -325,6 +325,26 @@ Deno.test("exceptions", async (t) => {
325325 } ) ;
326326} ) ;
327327
328+ Deno . test ( "instance method" , ( ) => {
329+ const { A } = python . runModule (
330+ `
331+ class A:
332+ def b(self):
333+ return 4
334+ ` ,
335+ "cb_test.py" ,
336+ ) ;
337+
338+ const [ m , cb ] = python . instanceMethod ( ( _args , self ) => {
339+ return self . b ( ) ;
340+ } ) ;
341+ // Modifying PyObject modifes A
342+ PyObject . from ( A ) . setAttr ( "a" , m ) ;
343+
344+ assertEquals ( new A ( ) . a . call ( ) . valueOf ( ) , 4 ) ;
345+ cb . destroy ( ) ;
346+ } ) ;
347+
328348Deno . test ( "callbacks have signature" , async ( t ) => {
329349 const inspect = python . import ( "inspect" ) ;
330350
You can’t perform that action at this time.
0 commit comments