I am trying to call a python function by passing it a HashMap from java (groovy). The python function squares each value in the input map and returns a dictionary of squares with the same keys.
JythonTest.groovy
import org.python.util.PythonInterpreter import org.python.core.*; class JythonTest { static main(def args) { PythonInterpreter pi; pi = new PythonInterpreter() pi.exec("from py1 import square3") PyFunction pf = (PyFunction)pi.get("square3") def map = ["value1":1,"value2":2,"value3":3]
py1.py
def square3(map): squareMap = {} for k,v in map.items():
But I get the following error:
Exception in thread "main" Traceback (most recent call last): File "__pyclasspath__/py1.py", line 3, in square3 java.lang.ClassCastException: java.lang.String cannot be cast to org.python.core.PyObject at org.python.core.PyDictionary.dict_items(PyDictionary.java:659) at org.python.core.PyDictionary$dict_items_exposer.__call__(Unknown Source) at org.python.core.PyObject.__call__(PyObject.java:449) at py1$py.square3$1(__pyclasspath__/py1.py:5) at py1$py.call_function(__pyclasspath__/py1.py) at org.python.core.PyTableCode.call(PyTableCode.java:167) at org.python.core.PyBaseCode.call(PyBaseCode.java:138) at org.python.core.PyFunction.__call__(PyFunction.java:413) at org.python.core.PyFunction.__call__(PyFunction.java:408) at org.python.core.PyFunction$__call__.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122) at JythonTest.main(JythonTest.groovy:16) java.lang.ClassCastException: java.lang.ClassCastException: java.lang.String cannot be cast to org.python.core.PyObject
The exception stack trace says that the exception is in the line of the python 3 file. But when I call the python function from python itself, say by py1.py line below at the end of py1.py :
a = square3({"val1":1,"val2":2}) print(a)
I get the following output:
{'val2': 4, 'val1': 1}
So why the python function call from java fails? I donβt understand what is going on here. Why call pf.__call__(pyDict) throw such an exception?
source share