Passing and Returning Java Map to GraalVM python

26 Views Asked by At

I want to pass java map to python code and access the map values in python, and then store the results in a map, then access the results in Java. I'm stuck with the first step to pass java map to python.

I have tried with the following code, but didn't work

import java.util.HashMap;
import java.util.Map;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;

public class PythonJavaMap {
  public static void main(String[] args) {
    Map<String, String> javaMap = new HashMap<>();
    javaMap.put("key1", "value1");
    javaMap.put("key2", "value2");

    try (Context context = Context.create()) {
      context.getBindings("python").putMember("java_map", javaMap);
      Value result = context.eval("python", "for key, value in java_map.items(): print(value)");
    }
  }
}

I got the following error

Exception in thread "main" AttributeError: foreign object has no attribute 'items'
    at <python> <module>(Unknown)
    at org.graalvm.polyglot.Context.eval(Context.java:428)
    at com.mindSynth.PythonJavaMap.main(PythonJavaMap.java:18)
1

There are 1 best solutions below

0
Jay On

The following code works, it turns out I need enable host access.


import java.util.HashMap;
import java.util.Map;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;

public class PythonMapMap {
  @FunctionalInterface interface MapFunction { Map my_function(Map input); }

  public static void main(String[] args) {
    Context context = Context.newBuilder().allowHostAccess(true).build();

    Value function = context.eval("python",
        """
            def my_function(fname):
                print(fname)
                methods_and_attributes = dir(fname)
                print(methods_and_attributes)
                print(fname["test"])
                print(fname.get("test"))
                result = HashMap()
                result['foo'] = 5
                return result;
            """);
    Map<String, Object> input = new HashMap<>();
    input.put("test", "test_value");
    System.out.println(function.as(MapFunction.class)
        .my_function(input));
  }
}