@@ -319,7 +319,10 @@ class Main {
319319}
320320` ` `
321321#### Interop Types
322- The ` register_interop_type` API allows the usage of python classes for foreign objects:
322+ The ` register_interop_type` API allows the usage of python classes for foreign objects.
323+ The type of such a foreign object will no longer be ` foreign` .
324+ Instead, it will be a generated class with the registered python classes and ` foreign` and as super classes.
325+ This allows mapping foreign methods and attributes to Python's magic method or more idiomatic Python code.
323326
324327` ` ` java
325328package org .example ;
@@ -366,6 +369,7 @@ import java
366369from polyglot import register_interop_type
367370
368371print (my_java_object .getX ()) # 42
372+ print (type (my_java_object)) # < class ' foreign' >
369373
370374class MyPythonClass :
371375 def get_tuple (self ):
@@ -376,13 +380,23 @@ foreign_class = java.type("org.example.MyJavaClass")
376380register_interop_type (foreign_class, MyPythonClass)
377381
378382print (my_java_object .get_tuple ()) # (42 , 17 )
383+ print (type (my_java_object)) # < class ' polyglot.Java_org.example.MyJavaClass_generated' >
384+ print (type (my_java_object).mro ()) # [generated_class, MyPythonClass, foreign, object]
379385
380386class MyPythonClassTwo :
381- def __str__ (self ):
382- return f" MyJavaInstance(x={self.getX()}, y={self.getY()}"
387+ def get_tuple (self ):
388+ return (self .getY (), self .getX ())
389+ def __str__ (self ):
390+ return f" MyJavaInstance(x={self.getX()}, y={self.getY()}"
391+
392+ # If ' allow_method_overwrites=False' or not given, this would lead to an error due to the method conflict of ' get_tuple'
393+ register_interop_type (foreign_class, MyPythonClassTwo, allow_method_overwrites= True)
383394
384- register_interop_type (foreign_class, MyPythonClassTwo)
395+ # A newly registered class will be before already registered classes in the mro.
396+ # It allows overwriting methods from already registered classes with the flag ' allow_method_overwrites=True'
397+ print (type (my_java_object).mro ()) # [generated_class, MyPythonClassTwo, MyPythonClass, foreign, object]
385398
399+ print (my_java_object .get_tuple ()) # (17 , 42 )
386400print (my_java_object) # MyJavaInstance (x= 42 , y= 17 )
387401` ` `
388402
0 commit comments