Skip to content

Commit ed1d7cc

Browse files
committed
add better documentation of the class merge algorithm
1 parent e9d7a80 commit ed1d7cc

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

docs/user/Interoperability.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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
325328
package org.example;
@@ -366,6 +369,7 @@ import java
366369
from polyglot import register_interop_type
367370

368371
print(my_java_object.getX()) # 42
372+
print(type(my_java_object)) # <class 'foreign'>
369373

370374
class MyPythonClass:
371375
def get_tuple(self):
@@ -376,13 +380,23 @@ foreign_class = java.type("org.example.MyJavaClass")
376380
register_interop_type(foreign_class, MyPythonClass)
377381

378382
print(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

380386
class 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)
386400
print(my_java_object) # MyJavaInstance(x=42, y=17)
387401
```
388402

0 commit comments

Comments
 (0)