ninia / jep

Embed Python in Java
Other
1.28k stars 145 forks source link

Passing HashMap as an argument of type dict #461

Closed jep-learner closed 1 year ago

jep-learner commented 1 year ago

Describe the problem I am having a problem passing an object of type HashMap as an argument of typedict.

Python module testdict:

def test_dict(param_dict={}):
    for key, value in param_dict.items():
        pass

Java class:

package org.example;

import jep.Interpreter;
import jep.JepConfig;
import jep.SharedInterpreter;

import java.util.HashMap;

public class ExampleApp {
    public static void main(String[] args) {
        JepConfig config = new JepConfig();
        try (Interpreter interp = new SharedInterpreter()) {
            interp.exec("import testdict");
            HashMap arg = new HashMap();
            interp.set("param_dict", arg);
            interp.exec("testdict.test_dict(param_dict)");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

Exception:

jep.JepException: <class 'AttributeError'>: 'HashMap' object has no attribute 'items'
    at .../testdict.test_dict(testdict.py:2)
    at <string>.<module>(<string>:1)
    at jep.Jep.exec(Native Method)
    at jep.Jep.exec(Jep.java:341)
    at org.example.ExampleApp.main(ExampleApp.java:16)

Could you please advise how to fix this issue on the Java side? The Python function signature can not be changed.

Thank you.

Environment (please complete the following information):

bsteffensmeier commented 1 year ago

Java Maps are not converted to dicts and while some dict functionality is added by jep they are not completely interchangeable. You can write python code to convert the map to a dict. You could use Map.forEach() to convert a map to a dict without much code:

interp.exec("real_param_dict = {}")
interp.exec("param_dict.forEach(lambda k,v: real_param_dict.update({k:v}))"
interp.exec("param_dict = real_param_dict")

There is some more information on working with maps in python in this post.

jep-learner commented 1 year ago

Thank you!